如何在 Python 3.7 中使用 Pygame 显示装有 Pillow 的图像? [英] How to display Images loaded with Pillow with Pygame in Python 3.7?
问题描述
我使用
from PIL import Image
myImage = Image.open("myImageDirectory.png")
所以 myImage 现在被导入为 png 文件.但我想使用 Pygame 将它显示到屏幕上.通常我使用
So myImage is now imported as a png file. But I want to display it to the Screen using Pygame. Normally I use
import pygame
win = pygame.display.set_mode((500, 500))
win.blit(myImage, (50, 50))
现在我得到错误,该函数需要一个表面,而不是一个 png 文件.有没有人知道如何将图像转换为表面或如何显示它?
Now I get the Error that the function needs a surface, not a png File. Has anyone an idea how I can convert the image to a surface or how I can display it?
我还没有尝试太多,因为我没有找到任何可以解决我的问题的方法.
I tried not much yet because I didn't found anything that could solve my problem.
推荐答案
使用 Image.tobytes()
获取作为字节对象的图像数据和 pygame.image.fromstring()
将数据加载到 pygame.Surface
对象:
Use Image.tobytes()
get the image data as a bytes object and pygame.image.fromstring()
to load the data to an pygame.Surface
object:
from PIL import Image
import pygame
pilImage = Image.open("myImageDirectory.png")
myImage = pygame.image.fromstring(pilImage.tobytes(), pilImage.size, pilImage.mode)
这篇关于如何在 Python 3.7 中使用 Pygame 显示装有 Pillow 的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!