I want to determine if a puush.me image (Links are no HTML, just the image) is png, jpg or gif. Is there a way to do that n python? Urllib does not seem to open images and detecting them.
Open a picture via URL and detecting if it is png, jpg or gif in Python?
2.8k Views Asked by user3760874 At
4
There are 4 best solutions below
0
On
To determine what type of file it is from the webserver itself before downloading, you can check the Content-Type header.
Python 2.x example
import urllib2
my_url = "http://upload.wikimedia.org/wikipedia/en/b/bc/Wiki.png" #example image
request = urllib2.urlopen(my_url)
mime = request.info()['Content-type']
if mime.endswith("png"):
print("Image is a png")
elif mime.endswith("jpeg"):
print("Image is a jpg")
elif mime.endswith("gif"):
print("Image is a gif")
#Image is a png
1
On
You can use the imghdr library (included in the Python Standard Library) to determine the type of an image.
import cStringIO
import imghdr
import urllib2
url = "http://www.gnu.org/graphics/gerwinski-gnu-head.png"
response = urllib2.urlopen(url)
data = cStringIO.StringIO(response.read())
print(imghdr.what(data))
If you've got the data of the file, you could check the first few bytes for magic number signiture:
For example, Python3.x: