pythondjangopython-imaging-librarybytestream

Python image in `bytes` - get height, width


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

Solution

  • 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