reza
reza

Reputation: 6358

What is the equivalent of reading a jpg file using PIL image?

Using python 3.10.

My issue is I read a jpg file as a binary file and I get a bytes array. I have the following code:

from PIL import Image

def get_image_bytes_from_file(filename: str):
    with open(filename, "rb") as f:
        image_read = f.read()
        return image_read


input_file = './image.jpg'

image = Image.open(input_file)
pil_bytes = image.tobytes()

normal_read_bytes = get_image_bytes_from_file(input_file)

print('hi')

what call do I need to make to pil_bytes to be equal to normal_read_bytesenter code here

How do I do that?

Upvotes: 1

Views: 853

Answers (1)

Mark Setchell
Mark Setchell

Reputation: 208003

When you do this:

with open('image.jpg', "rb") as f:
    JPEG = f.read()

your variable called JPEG will contain a full JPEG image:

  • a Start of Image marker, SOI (0xFF 0xD8)
  • an APP0 marker, (0xFF 0xE0) with the JFIF version and the horizontal and vertical dpi
  • quantisation tables and Huffman tables
  • possibly the EXIF data with GPS latitude, longitude, camera make, camera model, date of photo, etc.
  • a Start of Frame marker, SOF0 with bits per pixel, image width and height, number of channels, sampling factors
  • JPEG-compressed pixels
  • EOI, End of Image marker (0xFF 0xD9)

That is a complete, JPEG-encoded, compressed image with a bunch of metadata.


When you do this, PIL will decompress the JPEG data into a fully expanded, in-memory representation, ready for processing:

im = Image.open('image.jpg')
pixels = im.tobytes()

your variable pixels will contain purely the uncompressed pixels of your image, in RGB order starting from the top-left of your image. There will be no EXIF data, no date, no GPS, no comments, no camera make, no camera model or lens data. It will always have the full, uncompressed size:

height in pixels * width width in pixels * 3 bytes

So, if the top line of your image is white, it will start:

0xFF 0xFF 0xFF 0xFF ...

it is pure pixel data.


Hopefully you can now see the difference between the two things, so what is it that you want to do...

Upvotes: 2

Related Questions