2

I'm trying to detect width and height of an image before saving it to the database and S3. The image is in bytes.

This is an example of an image before saved to Django ImageField:

enter image description here

NOTE: I don't want to use ImageFields height_field and width_field as it slows down the server tremendously for some reason so I want to do it manually.

The image is downloaded using requests:

def download_image(url):
    r = requests.get(url, stream=True)
    r.raw.decode_content = True
    return r.content
Milano
  • 18,048
  • 37
  • 153
  • 353
  • the best solution I can think of is trying to get the image meta data client-side and store it as integers. There is a way to use the image stream, but it would require you to detect the format of the image, and then decode the part of the file. There are libraries that do that, but in any case it will remain slower than the first approach. You may also look here: https://stackoverflow.com/questions/1164930/image-resizing-with-django/1164988#1164988 – tstoev Aug 29 '21 at 13:00

1 Answers1

4

To get the width/height of an image from a binary string, you would have to try to parse the binary string with an image library. The easiest one for the job would be pillow.

import requests
from PIL import Image
import io


def download_image(url):
    r = requests.get(url, stream=True)
    r.raw.decode_content = True
    return r.content


image_url = "https://picsum.photos/seed/picsum/300/200"
image_data = download_image(image_url)

image = Image.open(io.BytesIO(image_data))
width = image.width
height = image.height
print(f'width: {width}, height: {height}')
width: 300, height: 200
Finomnis
  • 18,094
  • 1
  • 20
  • 27