Detecting if an image is really an image
About Technique
HTTP protocol has really cool methods such as HEAD. HEAD method allows you to get only head data instead of head and body. Head data contains mimetype of the body, so we can rely on it to detect if it's really an image. Let's get it with JavaScript...
The Code
Sync Example
request = new XMLHttpRequest()
request.open 'HEAD', 'http://upload.wikimedia.org/wikipedia/commons/5/5b/Ultraviolet_image_of_the_Cygnus_Loop_Nebula_crop.jpg', false
request.send()
mimetype = request.getResponseHeader('content-type')
if mimetype.split('/').shift() is 'image'
alert 'Image!'
else
alert 'Not Image!'
Async Example
# Async example
request = new XMLHttpRequest()
request.onreadystatechange = ->
if request.readyState is 4
mimetype = request.getResponseHeader('content-type')
if mimetype.split('/').shift() is 'image'
alert 'Image!'
else
alert 'Not Image!'
request.open 'HEAD', 'http://upload.wikimedia.org/wikipedia/commons/5/5b/Ultraviolet_image_of_the_Cygnus_Loop_Nebula_crop.jpg', true
request.send()
As you can see, you can even detect huge images very quickly.
Written by Berat Dogan
Related protips
1 Response
Well, I think it's just identifying whether the header begins from "image" or not. The header is able to be modified by the backend developer. e,g, Changing the header content-type to image/png, but the actual data is able to be application/json.
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Javascript
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#