Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get binary image data from PIL.Image?

I've opened an image in PIL like so:

from PIL import Image

i = Image.open("image.jpg")

I need to access the raw contents of this file. How can I get the entire picture data, as if I would have done open(...).read()?

like image 964
Naftuli Kay Avatar asked Jan 07 '15 18:01

Naftuli Kay


People also ask

How can I get bytes from image in PIL?

In the above code, we save the im_resize Image object into BytesIO object buf . Note that in this case, you have to specify the saving image format because PIL does not know the image format in this case. The bytes string can be retrieved using getvalue() method of buf variable.

How do I open a byte image in Python?

If you have an entire image in a string, wrap it in a BytesIO object, and use open() to load it.

What does PIL image return?

The Image module provides a class with the same name which is used to represent a PIL image. The module also provides a number of factory functions, including functions to load images from files, and to create new images. Image. convert() Returns a converted copy of this image.


1 Answers

you can see this answer python Image PIL to binary Hex

The img object needs to be saved again; write it to another BytesIO object:

output = io.BytesIO()
img.save(output, format='JPEG')

then get the written data with the .getvalue() method:

hex_data = output.getvalue()
like image 73
xiaoyu2er Avatar answered Sep 25 '22 22:09

xiaoyu2er