首页 > 解决方案 > `bytes`中的Python图像 - 获取高度,宽度

问题描述

在将图像保存到数据库和 S3 之前,width我正在尝试检测图像。height图像在bytes.

这是保存到之前的图像示例Django ImageField

在此处输入图像描述

注意:我不想使用ImageFieldsheight_field并且width_field由于某种原因它极大地减慢了服务器的速度,所以我想手动进行。

使用请求下载图像:

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

标签: pythondjangopython-imaging-librarybytestream

解决方案


要从二进制字符串中获取图像的宽度/高度,您必须尝试使用​​图像库解析二进制字符串。最简单的工作将是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

推荐阅读