Do you want to check whether the download would be successful? Or do you want to check that what is downloaded is, in fact, an image?
In the former case, the only way to check is to try to access it and see what kind of HTTP response code you get. You can send an HTTP HEAD
request to get the response code without actually downloading the image, but if you're just going to go ahead and download the image anyway (if it's successful) then sending a separate HEAD
request seems like a waste of time (and bandwidth).
Alternatively, if you really want to check that what you're downloading is a valid image file, you have to read the whole file to check it for corruption. But if you just want to check that the file extension is accurate, it should be enough to check the first few bytes of the file. All GIF images start with the ASCII text GIF87
or GIF89
depending on which GIF specification is used. PNG images start with the ASCII text PNG
, and JPEG images have some magic number, which appears to be 0xd8ffe0ff
based on the JPEGs I looked at. (You should do some research and check that, try Wikipedia for links) Keep in mind, though, that to get even the first few bytes of the image, you will need to send an HTTP request which could return a 404 (and in that case you don't have any image to check).