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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
Async Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. ;)
Originally posted at https://coderwall.com/p/qdg71a/detecting-if-an-image-is-really-an-image
No comments:
Post a Comment