Home > Back-end >  How to get image from bytes in Python?
How to get image from bytes in Python?

Time:05-15

I have an image (jpeg). I get the bytes from it simply using open('img.jpg', 'rb'). And for instance I send that bytes to my friend. So which way using Python can he get conversely operation - from bytes the image? How to decode it?

  1. the way if he knows the format - JPEG for example.
  2. the way if he doesn't know the format. Is there any ways?

CodePudding user response:

Use the PIL module. More information in answers here: Decode image bytes data stream to JPEG

from PIL import Image
from io import BytesIO


with open('img.jpg', 'rb') as f:
    data = f.read()

    # Load image from BytesIO
    im = Image.open(BytesIO(data))

    # Display image
    im.show()

CodePudding user response:

If you don't want to use an external library, you can use the byte signature - which is the first few bytes of the file - to determine the image compression type.

Here are some common image formats.

img_types = {
    b'\xFF\xD8\xFF\xDB': 'jpg',
    b'\xFF\xD8\xFF\xE0': 'jpg',
    b'\xFF\xD8\xFF\xEE': 'jpg',
    b'\xFF\xD8\xFF\xE1': 'jpg',
    b'\x47\x49\x46\x38\x37\x61': 'gif',
    b'\x47\x49\x46\x38\x39\x61': 'gif',
    b'\x42\x4D': 'bmp',
    b'\x89\x50\x4E\x47\x0D\x0A\x1A\x0A': 'png'
}

with open('path/to/image', 'rb') as fp:
    img_bytes = fp.read()

for k, v in img_types.items():
    if img_bytes.startswith(k):
        img_type = v
        break
else:
    img_type = None

CodePudding user response:

Did you check this question and this one? They are very similar with your case. Also AFAIK original format of the image does not make any difference if you convert them into bytes. So linked questions/answers should be fine. However, if they are not working, please update your question.

  • Related