2

我正在尝试将图像转换为字符串到字节然后再转换回图像,但是某处发生了故障,我真的不知道是什么。我正在使用 Python 3.3 和 pygame。

我需要对字符串执行此操作的原因是因为稍后我计划将字符串导出到 XML 文件,并且当我拉取变量时,它无论如何都会以 unicode 字符串类型出现。

对于这个烦人的问题,任何帮助将不胜感激。

import pygame
pygame.init()
displaysurf = pygame.display.set_mode((500, 500))

dirtImg = pygame.image.load('1.gif')
dirtXY= dirtImg.get_size()
print(dirtXY)

dirtText = str(pygame.image.tostring(dirtImg,'RGBX',False))



dirtBytes = bytes(dirtText, 'utf8' )
print(type(dirtBytes))
#prints out <class 'bytes'>


testimg = pygame.image.fromstring(dirtBytes, dirtXY, 'RGBX')

错误信息

  Traceback (most recent call last):
      File "C:\Users\Derek\workspace\Test\test.py", line 18, in <module>

  testimg = pygame.image.fromstring(dirtBytes, dirtXY, 'RGBX')
      ValueError: String length does not equal format and resolution size

显然我不会随时更改图像,因此它必须在编码或解码为字节。如果有更好的方法,请告诉

4

1 回答 1

3

在与 ddaniels 聊天讨论后,我发现这是他正在使用的过程:

  • pygame 图像
  • --> pygame 字节串
  • --> 手动复制粘贴到 xml
  • --> 从 xml 读取
  • --> pygame 图像(此处失败)

我认为复制粘贴对于可能会发现这个问题的其他人来说不是一个通用的解决方案,所以我想办法从 pygame 图像到 xml 再回到 pygame。它在 Python 2 中更简单,但此代码适用于 Python 2 和 Python 3。

如果有人知道如何简化此过程,请告诉我。

import pygame
import base64
import xml.etree.ElementTree as ET
pygame.init()
dirt_image = pygame.image.load('dirt.gif')
dirt_xy = dirt_image.get_size()

# incantation starts here
# The result of tostring is a bytestring with basically binary data.
dirt_bytes = pygame.image.tostring(dirt_image, 'RGBX', False)
# b64 encode so that we have all printable characters in the string.
# Otherwise elementtree doesn't want to accept the content.
# The result is another byte string but with printable characters.
dirt_bytes_in_64 = base64.b64encode(dirt_bytes)
# in Python 3, ElementTree complains about bytestrings so we further encode
# it into utf-8. In Python 2, this is not necessary.
dirt_bytes_in_64_in_utf8 = dirt_bytes_in_64.decode('utf-8')

# ElementTree create, save, restore
root = ET.Element("root")
dirt = ET.SubElement(root, 'dirt')
dirt.set('bytes64utf8', dirt_bytes_in_64_in_utf8)
tree = ET.ElementTree(root)
tree.write('images.xml')
tree_restored = ET.parse('images.xml')
dirt_bytes_in_64_in_utf8_restored = tree_restored.find('dirt').get('bytes64utf8')

# Convert from utf-8 back to base64 bytestring.
dirt_bytes_in_64_restored = dirt_bytes_in_64_in_utf8_restored.encode('utf-8')
# Convert from base64 bytestring into the original binary bytestring
dirt_bytes_restored = base64.b64decode(dirt_bytes_in_64_restored)

# Shazam. (for me at least)
restored_image = pygame.image.fromstring(dirt_bytes_restored, dirt_xy, 'RGBX')
display_surf = pygame.display.set_mode((500, 500))
display_surf.blit(dirt_image, (0, 0))
display_surf.blit(restored_image, (32, 32))
pygame.display.flip()
于 2013-10-17T04:43:43.887 回答