获取图片的大小(宽高):BytesIO

获取图片的大小(宽高)

from io import BytesIO,StringIO
import requests
from PIL import Image
img_url = "http://imglf1.ph.126.net/pWRxzh6FRrG2qVL3JBvrDg==/6630172763234505196.png"
response = requests.get(img_url)
f = BytesIO(response.content)
img = Image.open(f)
print(img.size)

  

输出结果:

(500, 262)

理解一下 BytesIO 和StringIO

很多时候,数据读写不一定是文件,也可以在内存中读写。
StringIO顾名思义就是在内存中读写str。
BytesIO 就是在内存中读写bytes类型的二进制数据

例子中如果使用StringIO 即f = StringIO(response.text)会产生"cannot identify image file"的错误
当然上述例子也可以把图片存到本地之后再使用Image打开来获取图片大小

原文地址:https://www.cnblogs.com/andy9468/p/8337105.html