python - `bytes`中的Python图像 - 获取高度,宽度
问题描述
在将图像保存到数据库和 S3 之前,width
我正在尝试检测图像。height
图像在bytes
.
这是保存到之前的图像示例Django
ImageField
:
注意:我不想使用ImageField
sheight_field
并且width_field
由于某种原因它极大地减慢了服务器的速度,所以我想手动进行。
使用请求下载图像:
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
推荐阅读
- javascript - 从 Google Cloud Function 检查 Google Speech API 操作
- android - 我们如何在设备时间更改时刷新 /.info/serverTimeOffset?
- sql - SQL Server:从一个查询中获取多个最小值/最大值
- bitbucket - Bitbucket- Webhook 返回 302
- git - 在 Mac 上找不到机器级 gitconfig 文件
- rest - 如何获取属于一组 LINK_IDS 的交通标志
- unit-testing - vue-test-utils:如何在 mount() 生命周期钩子(使用 vuex)中测试逻辑?
- javascript - 递归地展平对象数组
- javascript - Chrome 来源未显示从 Typescript 生成且具有源映射的文件
- mysql - Tomcat/休眠配置