无法识别图像文件<_io.BytesIO对象在0x7f15d3b20400>
我的Python服务器通过套接字从客户端接收一个base64格式的图片,我想解码这个图片并用tkinter显示出来。有时候图片能成功解码并显示出来,但有时候会出现这个错误信息:cannot identify image file <_io.BytesIO object at 0x7f15d3b20400>
。
def display_image_of_base64(self, base64_image):
if not self.is_base64(base64_image):
print("Invalid Base64 string")
return False
try:
image_bytes = base64.b64decode(base64_image.decode("utf8"))
except binascii.Error:
return False
try:
try:
image_stream = io.BytesIO(image_bytes)
image_stream.seek(0)
pil_image = Image.open(image_stream)
except OSError as e:
print(e)
return False
tk_image = ImageTk.PhotoImage(pil_image)
except ValueError:
return False
print(image_bytes)
self.label.config(image=tk_image)
self.label.image = tk_image
这是一个解码成功后图片的例子:在这里输入图片描述。图片中不应该有灰色的部分,其他的内容应该都能正常显示。
我想解决这个错误:'cannot identify image file <_io.BytesIO object at 0x7f15d3b20400>',并希望能正确显示接收到的base64编码的图片。
谢谢你的帮助!!!
1 个回答
0
我解决了这个问题。问题在于,我发送的图片被自动拆分成了几个小包,尽管我只发送了一次。因此,服务器只收到了图片的一部分,直接显示了这部分图片,没有等到其他的小包。为了让服务器知道图片是完整的,我在客户端发送的图片末尾加了一段文字,表示图片已经发送完毕。这样,服务器就会收到一些图片的部分,然后把它们拼在一起,直到收到的消息中出现了这个表示图片完整的文字。