Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 869
murgatroid99 Avatar asked Aug 18 '12 17:08

murgatroid99


People also ask

How do I open a PIL image?

Image. open() Opens and identifies the given image file. This is a lazy operation; this function identifies the file, but the file remains open and the actual image data is not read from the file until you try to process the data (or call the load() method).

How do I open an image URL?

On your computer, go to images.google.com. Search for the image. In Images results, click the image. At the top of your browser, click the address bar to select the entire URL.

What is PIL image format?

Python Imaging Library is a free and open-source additional library for the Python programming language that adds support for opening, manipulating, and saving many different image file formats. It is available for Windows, Mac OS X and Linux. The latest version of PIL is 1.1.

How do I open a URL in python?

just open the python interpreter and type webbrowser. open('http://www.google.com') and see if it does what you want.


2 Answers

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) 
like image 176
Snakes and Coffee Avatar answered Sep 22 '22 00:09

Snakes and Coffee


Using Python requests:

from PIL import Image from StringIO import StringIO import requests  r = requests.get("http://a/b/c") im = Image.open(StringIO(r.content)) im.size 
like image 40
Matt Parrilla Avatar answered Sep 19 '22 00:09

Matt Parrilla