Is there a way to quickly fetch an image from provided link with js and see if it is valid? i.e see if it links to plain image like this example or catch cases when some websites redirect you to other pages i.e. not to image.
Asked
Active
Viewed 1,174 times
1
-
check if it ends with .jpg or .png?? – Mike Lammers Mar 08 '16 at 11:39
-
Check the mimetype of the response? And what do you mean by "forbidden"? – clinei Mar 08 '16 at 11:39
-
you can load the image inside a
– atmd Mar 08 '16 at 11:43
2 Answers
2
For simple checking if it is a image link you can use this.
function checkURL(url) {
return(url.match(/\.(jpeg|jpg|gif|png)$/) != null);
}
When you want a bullet proof way of checking if the image is a legit image you can use this.
http://jsfiddle.net/jfriend00/qKtra/
JS:
function testImage(url, callback, timeout) {
timeout = timeout || 5000;
var timedOut = false, timer;
var img = new Image();
img.onerror = img.onabort = function() {
if (!timedOut) {
clearTimeout(timer);
callback(url, "error");
}
};
img.onload = function() {
if (!timedOut) {
clearTimeout(timer);
callback(url, "success");
}
};
img.src = url;
timer = setTimeout(function() {
timedOut = true;
callback(url, "timeout");
}, timeout);
}
function record(url, result) {
document.body.innerHTML += "<span class='" + result + "'>" +
result + ": " + url + "</span><br>";
}
testImage("http://photos.smugmug.com/photos/344291068_HdnTo-Ti.jpg", record);
testImage("http://photos.smugmug.com/photos/invalid344291068_HdnTo-Ti.jpg", record);
testImage("http://www.cnn.com/foo.jpg", record);
testImage("https://www.google.com/images/srpr/logo3w.png", record);
CSS:
.success {
color: green;
}
.error, .timeout {
color: red;
}

Mike Lammers
- 542
- 9
- 27
2
here's a trick using jquery:
$("<img/>")
.on('load', function() { console.log("image loaded correctly"); })
.on('error', function() { console.log("error loading image"); })
.attr("src", "image_url_here");
found the solution here: Check if an image is loaded (no errors) in JavaScript

Community
- 1
- 1

Ronen Ness
- 9,923
- 4
- 33
- 50