ValueError: 字节长度与格式和分辨率大小不相等

huangapple go评论57阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年7月6日 17:34:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/76627437.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定