Say I have an imgur url like so: https://i.sstatic.net/nREgA.jpg
From the url I have no idea if this is a picture or a gif. I know I can add ".jpg" to the end of the file to get a direct link to the image but this will bring up the gif as well if the link happens to be a gif. How would I programmatically (using the imgur API or otherwise) check if the item at the url https://i.sstatic.net/nREgA.jpg or https://i.sstatic.net/nREgA.jpg.jpg is an image or a gif?
edit: I tried this
print(requests.head(submission.url + ".jpg").headers['Content-Type'])
but it complained with the following error:
KeyError: 'content-type'
implying content-type was not a key in the header. I printed the headers and confirmed this as they are the following:
{'Content-Length': '0', 'X-Served-By': 'cache-sjc3138-SJC', 'X-Cache': 'HIT', 'Accept-Ranges': 'bytes', 'X-Timer': 'S1498627080.598287,VS0,VE0', 'Server': 'cat factory 1.0', 'Retry-After': '0', 'Connection': 'close', 'X-Cache-Hits': '0', 'Location': 'https://i.imgur.com/APMnK9t.jpg', 'Cache-Control': 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0', 'Date': 'Wed, 28 Jun 2017 05:17:59 GMT', 'X-Frame-Options': 'DENY'}
I suppose I could check if content-length is not 0 to see if it is a gif? Thoughts?
Using the requests
library:
import requests
def get_content_type(url):
return requests.head(url).headers['Content-Type']
print(get_content_type('https://i.imgur.com/pCEoGjF.jpg')) # image/jpeg
print(get_content_type('https://i.imgur.com/kJNdeQv.jpg')) # image/gif