Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get image size without downloading it in Python

Tags:

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.

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.

Edit:

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).

like image 656
grotos Avatar asked Sep 18 '11 07:09

grotos


People also ask

How do I get the size of an image in Python?

open() is used to open the image and then . width and . height property of Image are used to get the height and width of the image.

How do I get the size of a file in Python?

Use the os. path. getsize('file_path') function to check the file size. Pass the file name or file path to this function as an argument.


1 Answers

I found the solution on this site to work well:

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 1:         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  print getsizes("http://www.pythonware.com/images/small-yoyo.gif") # (10965, (179, 188)) 
like image 99
jedierikb Avatar answered Nov 07 '22 01:11

jedierikb