Archive
Posts Tagged ‘image header’
Determine the dimensions of an image on the web without downloading it entirely
November 3, 2013
Leave a comment
Problem
You have a list of image URLs and you want to do something with them. You need their dimensions (width, height) BUT you don’t want to download them completely.
Solution
I found a nice working solution here (see the bottom of the linked page).
I copy the code here for future references:
#!/usr/bin/env python
import urllib
import ImageFile
def getsizes(uri):
# get file size *and* image size (None if not known)
file = urllib.urlopen(uri)
size = file.headers.get("content-length")
if size:
size = int(size)
p = ImageFile.Parser()
while True:
data = file.read(1024)
if not data:
break
p.feed(data)
if p.image:
return size, p.image.size
break
file.close()
return size, None
##########
if __name__ == "__main__":
url = "https://upload.wikimedia.org/wikipedia/commons/1/12/Baobob_tree.jpg"
print getsizes(url)
Sample output:
(1866490, (1164, 1738))
Where the first value is the size of the file in bytes, and the second is a tuple with width and height of the image in pixels.
Update (20140406)
I had to figure out the dimensions of some image files on my local filesystem. Here is the slightly modified version of the code above:
import ImageFile
def getsizes(fname):
# get file size *and* image size (None if not known)
file = open(fname)
size = os.path.getsize(fname)
p = ImageFile.Parser()
while True:
data = file.read(1024)
if not data:
break
p.feed(data)
if p.image:
return size, p.image.size
break
file.close()
return size, None
Usage:
size = getsizes(fname)[1]
if size:
# process it
Categories: python
image dimension, image header, image size
