Reputation: 3
I'm doing a little program in Python and I need to check if an URL returns an image.
I tried this:
from io import BytesIO
import PIL
userinput = input("Please input your image link")
def checkifimage(link):
try:
req = requests.get(link)
img = PIL.Image.open(BytesIO(req.content))
except:
pass
# returns false if it's not an image
return False
# returns true if there aren't any error, aka the url returns an image
return True
checkifimage(userinput)
but my code always returns False
even if the link is correct.
Upvotes: 0
Views: 101
Reputation: 3489
You can use the HEAD method instead of the GET method to only return the headers, and then check the content type. Of course, this only works if the server returns the proper MIME type.
import requests
def checkifimage(link):
response = requests.head(link)
return response.headers["Content-Type"].startswith("image/")
Upvotes: 1