PIL和pygame.image

pha*_*eim 4 python image python-imaging-library

我用PIL打开了一个图像,如

image = Image.open("SomeImage.png")
Run Code Online (Sandbox Code Playgroud)

在上面画一些文字,如

draw = ImageDraw.Draw(image)
draw.text(Some parameters here)
Run Code Online (Sandbox Code Playgroud)

然后保存为

image.save("SomeOtherName.png")
Run Code Online (Sandbox Code Playgroud)

使用pygame.image打开它

this_image = pygame.image.load("SomeOtherName.png")
Run Code Online (Sandbox Code Playgroud)

我只是想在不保存的情况下这样做..这可能吗?保存然后加载需要花费大量时间(0.12秒是的,这就像我有多个需要此操作的图像一样).可以超越保存方法吗?

mii*_*lek 8

你可以使用fromstring()来自的功能pygame.image.根据文档,以下内容应该有效:

image = Image.open("SomeImage.png")
draw = ImageDraw.Draw(image)
draw.text(Some parameters here)

mode = image.mode
size = image.size
data = image.tostring()

this_image = pygame.image.fromstring(data, size, mode)
Run Code Online (Sandbox Code Playgroud)

  • 只需注意:image.tostring()将不再有效,请使用image.tobytes() (6认同)

Rab*_*d76 7

遗憾的是,接受的答案不再有效,因为Image.tostring()已被删除。它已被 取代Image.tobytes()。请参阅枕头Image模块

PILImage转换为pygame.Surface对象的函数:

def pilImageToSurface(pilImage):
    return pygame.image.fromstring(
        pilImage.tobytes(), pilImage.size, pilImage.mode).convert()
Run Code Online (Sandbox Code Playgroud)

建议convert()表面具有相同的像素格式的显示表面


最小的例子:

import pygame
from PIL import Image

def pilImageToSurface(pilImage):
    return pygame.image.fromstring(
        pilImage.tobytes(), pilImage.size, pilImage.mode).convert()

pygame.init()
window = pygame.display.set_mode((500, 500))
clock = pygame.time.Clock()

pilImage = Image.open('myimage.png')
pygameSurface = pilImageToSurface(pilImage)

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    window.fill(0)
    window.blit(pygameSurface, pygameSurface.get_rect(center = (250, 250)))
    pygame.display.flip()
Run Code Online (Sandbox Code Playgroud)