与 PIL 一起使用

当你必须同时使用 PIL 和 Pygame 因为它们都缺少功能时,你需要一种在 Pygame Surfaces 和 PIL Images 之间进行转换的方法,最好不要将它们写入磁盘。

为此,你可以使用两个库中提供的 tostringfromstring 函数。

从 PIL 转换为 Pygame:

strFormat = 'RGBA'
raw_str = image.tostring("raw", strFormat)
surface = pygame.image.fromstring(raw_str, image.size, strFormat)

从 Pygame 转换为 PIL:

strFormat = 'RGBA'
raw_str = pygame.image.tostring(surface, strFormat, False)
image = Image.frombytes(strFormat, surface.get_size(), raw_str)