英文:
ValueError: Bytes length does not equal format and resolution size
问题
So, I was creating some pygame
program, and I wanted to embed a .png
image with pygame.image.fromstring
but I keep getting the error above. I have tried other things like frombytes
and changing the size iterables but it won't work. The code I used to convert the image:
import base64
with open("my_image.png", "rb") as imageFile:
bytes = base64.b64encode(imageFile.read())
print(bytes)
And the image surface:
imageBytes = b'imagedata'
image = pygame.image.fromstring(imageBytes, (width,height), "RGBA")
After I converted my image of choice, I simply copied the output and pasted it in vs-code
and it returns the error message. How can I fix this? Help is appreciated!
英文:
So, I was creating some pygame
program, and I wanted to embed a .png
image with pygame.image.fromstring
but I keep getting the error above. I have tried other things like frombytes
and changing the size iterables but it won't work. The code I used to convert the image:
import base64
with open("my_image.png", "rb") as imageFile:
bytes = base64.b64encode(imageFile.read())
print(bytes)
And the image surface:
imageBytes = b'imagedata'
image = pygame.image.fromstring(imageBytes, (width,height), "RGBA")
After I converted my image of choice, I simply copied the output and pasted it in vs-code
and it returns the error message. How can I fix this? Help is appreciated!
答案1
得分: 1
使用 pygame.image.fromstring(imageBytes...)
不会起作用,因为该函数期望字符串采用特定的格式。
要获取适用于 fromstring
的字符串,您必须将图像加载到一个 Surface
中,然后使用 pygame.image.tostring
(或 tobytes
/frombytes
对应项)。
您加载图像并将其转换为Base64编码的字符串,因此您实际上可以解码它并使用 pygame.image.load
进行加载,就像这样:
import io
image = pygame.image.load(io.BytesIO(base64.b64decode(imageBytes)))
英文:
Using pygame.image.fromstring(imageBytes...)
won't work because this function expects the string to be in a certain format.
To get a string that works with fromstring
you have to load the image into a Surface
and then use pygame.image.tostring
(or the tobytes
/frombytes
counterparts).
You load your image and convert it into a base64 encoded string, so you could actually decode it back and load it with pygame.image.load
, like this:
import io
image = pygame.image.load(io.BytesIO(base64.b64decode(imageBytes)))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论