How do I open an image from the internet in PIL?

murgatroid99 picture murgatroid99 · Aug 18, 2012 · Viewed 33.5k times · Source

I would like to find the dimensions of an image on the internet. I tried using

from PIL import Image
import urllib2 as urllib
fd = urllib.urlopen("http://a/b/c")
im = Image.open(fd)
im.size

as suggested in this answer, but I get the error message

addinfourl instance has no attribute 'seek'

I checked and objects returned by urllib2.urlopen(url) do not seem to have a seek method according to dir.

So, what do I have to do to be able to load an image from the Internet into PIL?

Answer

Snakes and Coffee picture Snakes and Coffee · Aug 18, 2012

You might consider using io.BytesIO for forward compatibility.
The StringIO and cStringIO modules do not exist in Python 3.

from PIL import Image
import urllib2 as urllib
import io

fd = urllib.urlopen("http://a/b/c")
image_file = io.BytesIO(fd.read())
im = Image.open(image_file)