Python изображение в `байтах` - получить высоту, ширину

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:

введите описание изображения здесь

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.

Изображение загружается с помощью запросов:

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

Чтобы получить ширину/высоту изображения из двоичной строки, необходимо попытаться разобрать двоичную строку с помощью библиотеки изображений. Проще всего для этой задачи подойдут 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
Вернуться на верх