Wednesday, June 10, 2015

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.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()
view raw async.coffee hosted with ❤ by GitHub

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()
view raw async.coffee hosted with ❤ by GitHub

As you can see, you can even detect huge images very quickly. ;)

Originally posted at https://coderwall.com/p/qdg71a/detecting-if-an-image-is-really-an-image

No comments:

Post a Comment