Skip to main content
 首页 » 编程设计

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

2024年11月01日23myhome

我正在尝试将图像转换为字符串,再转换为字节,然后再转换回图像,但某处出现问题,我真的不知道是什么。我正在使用 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 

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

请您参考如下方法:

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