Mil*_*ano 2 python django python-imaging-library bytestream
我试图在将图像保存到数据库和 S3 之前检测width它height。该图像位于bytes.
这是保存到之前的图像示例Django ImageField:
注意:我不想使用ImageFields height_field,width_field因为它由于某种原因极大地减慢了服务器速度,所以我想手动执行。
使用请求下载图像:
def download_image(url):
r = requests.get(url, stream=True)
r.raw.decode_content = True
return r.content
Run Code Online (Sandbox Code Playgroud)
要从二进制字符串获取图像的宽度/高度,您必须尝试使用图像库解析二进制字符串。这项工作最简单的一个是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}')
Run Code Online (Sandbox Code Playgroud)
width: 300, height: 200
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2612 次 |
| 最近记录: |