Search code examples
pythonsocketstkinter

cannot identify image file <_io.BytesIO object at 0x7f15d3b20400>


My python server receives a base64 image via a socket from the client and I want to decode the image and display it with tkinter. Sometimes the image can be decoded and the image is displayed in some parts and sometimes this error message is displayed: cannot identify image file <_io.BytesIO object at 0x7f15d3b20400>. This is how my code looks like:

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

Here is an example of what the image looks like when the decoding works: Enter image description here The gray color should not be present. The rest of the screen should be present

I want to fix this error: 'cannot identify image file <_io.BytesIO object at 0x7f15d3b20400>' and want to display the received base64-encoded image correctly.

Thank You for your help!!!


Solution

  • I solved the problem. The problem was that the image that was sent was automatically split into several packages, although i only sent it once. Therefore, the server only received a part of the image and displayed the image directly and did not wait for the other packages, so I added an an text at the end of the image which was sent by the client which should indicate that the image is complete. The server then received some parts of the image and put them together until the text at the end of the base64 string was in the message which was sent to indicate the image was sent completely.