简体   繁体   中英

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

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

If you want to get the actual bytes of the image, just use i.tobytes() . This is with Pillow , I'm not sure if it's in the original PIL module, but from the docs it should be.

In PIL :

Image.open(path).convert('1')

As mentioned in doc

1 mode is for (1-bit pixels, black and white, stored with one pixel per byte)

PIL uses a lazy opening mechanism, in which the file contents are only read when needed. For doing that, it probably keeps the file reference in some internal (private) attribute.

Even if this attribute is accessible, it certainly is not exposed as part of the official PIL API - and it certainly is not meant to be used in this way.

Once the data is read, the file contents are decoded, and kept in memory as pixel values (which is usually what is desired when dealing with images). The library certainly does not keep the undecoded file data in a data structure in memory, as it would be meaningless.

If you want the raw file contents, you are likely processing the image with some other module, or storing it, or iterating over the data in a form that is agnostic to the actual image contents - can't you just open the file back with a regular "open"?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM