如何用XML存储和读取字节字符串(PyGame图像)?我得到ValueError或TypeError(无法序列化)。

2024-10-03 02:39:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图把一个图像转换成一个字符串,再转换成一个字节,然后再转换成一个图像,但是某处有东西坏了,我真的不知道是什么。我使用的是python3.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')

错误信息

^{pr2}$

显然,我不改变图像在任何时候,所以它必须在编码或解码字节。如果有更好的办法,那就告诉我


Tags: 文件字符串图像image字节bytesxmlpygame
1条回答
网友
1楼 · 发布于 2024-10-03 02:39:06

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

  • pygame图像
  • >;pygame bytestring
  • >;手动复制粘贴到xml
  • >从xml读取
  • >;游戏映像(此处失败)

我认为复制粘贴对于其他人来说并不是一个通用的解决方案,所以我想办法从pygame映像到xml再回到pygame。在Python2中它更简单,但是这段代码同时适用于Python2和Python3。在

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

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

相关问题 更多 >