在 python/pygame 中将字符串作为图像打开

Opening string as image in python/pygame

我已将图像保存为字符串:

import base64, os

with open(os.path.join("sprites","asteroids.png"), "rb") as imageFile:
    str_file = base64.b64encode(imageFile.read())

with open(os.path.join("sprites","asteroids_string.s "), "wb") as stringFile:
    stringFile.write(str_file)

我想在不同的项目中打开字符串并将其作为图像加载。我尝试了两种方法:

只需 self.image = pygame.image.fromstring(os.path.join("sprites", "asteroids_string.s "), GRID, "RGB") 然后我得到 TypeError: must be bytes, not str

with open(os.path.join("sprites","asteroids_string.s "), "rb") as stringFile:
       self.asteroid_string = stringFile.read()
self.image = pygame.image.fromstring(self.asteroid_string, GRID, "RGB")

然后我得到 ValueError: String length does not equal format and resolution size

我的错误在哪里?

您将 PNG 保存为字符串。 PNG 表示 headers 的压缩图像。

fromstring 需要没有 headers.

的未压缩图像字符串

可能只有 pygame.image.tostring 可以为 fromstring

创建正确的字符串