How to check if a URL goes to an image?

Question:

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.

Asked By: Antogamer

||

Answers:

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/")
Answered By: pigrammer
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.