Archive

Posts Tagged ‘image size’

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

Get the size (dimension) of an image

April 4, 2011 Leave a comment

Problem
You want to get the size (dimension) of an image.

Solution
We will use the Pillow package here, which is the successor of PIL.

from PIL import Image  # uses pillow

image_file = "something.jpg"
im = Image.open(image_file)
print im.size   # return value is a tuple, ex.: (1200, 800)

Related
If the image is on the web and you don’t want to download it, you can get the size of the image in bytes (see this post and get ‘Content-Length’).

Design a site like this with WordPress.com
Get started