Home > Blockchain >  Python PIL.Image.tobytes() gives invalid bytes for image
Python PIL.Image.tobytes() gives invalid bytes for image

Time:02-14

When I run this pillow code:

from PIL import Image

image = Image.open(BytesIO(some_bytes))
resized = image.resize((44, 44))
with open('filename.png', 'wb') as file:
    file.write(resized.tobytes())

No errors occur, but when I go to the file 'filename.png', my computer or any other software can't show the file, presumably because the bytes are invalid. Why is this so?

resized.tobytes() seems to return bytes, so I'm not sure why the picture's bytes are invalid. When I just write my normal bytes to filename.png it works, so that isn't invalid. Only the resized ones are.

Why is this so and how can I fix it?

CodePudding user response:

Answered by Jason Yang in comments -

Method Image.tobytes returns the raw image data from the internal storage. For compressed image data (e.g. PNG, JPEG) use save(), with a BytesIO parameter for in-memory data.

  • Related