无需在Python中下载即可获取图像大小 [英] Get image size without downloading it in Python
问题描述
如何在不实际下载的情况下获取图像尺寸?它甚至可能吗?
我有一个图片网址列表,我想为它分配宽度和大小。
How can I get dimensions of image without actually downloading it? Is it even possible? I have a list of urls of images and I want to assign width and size to it.
我知道有一种方法可以在本地进行(< a href =https://stackoverflow.com/questions/1507084/how-to-check-dimensions-of-all-images-in-a-directory-using-python>如何检查所有图像的尺寸目录使用python?),但我不想下载所有图像。
I know there is a way of doing it locally (How to check dimensions of all images in a directory using python?), but I don't want to download all the images.
编辑:
以下编辑。建议,我编辑了代码。我想出了此代码。不确定天气会下载整个文件还是只是一部分(我想要的)。
Following ed. suggestions, I edited the code. I came up with this code. Not sure weather it downloads whole file or just a part (as I wanted).
推荐答案
这是基于ed的答案和我在网上找到的其他东西。我遇到了与.read(24)的grotos相同的问题。从这里下载getimageinfo.py并从这里。
This is based on ed's answer mixed with other things I found on the web. I ran into the same issue as grotos with .read(24). Download getimageinfo.py from here and download ReSeekFile.py from here.
import urllib2
imgdata = urllib2.urlopen(href)
image_type,width,height = getimageinfo.getImageInfo(imgdata)
修改getimageinfo ...
Modify getimageinfo as such...
import ReseekFile
def getImageInfo(datastream):
datastream = ReseekFile.ReseekFile(datastream)
data = str(datastream.read(30))
#Skipping to jpeg
# handle JPEGs
elif (size >= 2) and data.startswith('\377\330'):
content_type = 'image/jpeg'
datastream.seek(0)
datastream.read(2)
b = datastream.read(1)
try:
while (b and ord(b) != 0xDA):
while (ord(b) != 0xFF): b = datastream.read(1)
while (ord(b) == 0xFF): b = datastream.read(1)
if (ord(b) >= 0xC0 and ord(b) <= 0xC3):
datastream.read(3)
h, w = struct.unpack(">HH", datastream.read(4))
break
else:
datastream.read(int(struct.unpack(">H", datastream.read(2))[0])-2)
b = datastream.read(1)
width = int(w)
height = int(h)
except struct.error:
pass
except ValueError:
pass
这篇关于无需在Python中下载即可获取图像大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!