與 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)