1

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.

Ilja
  • 44,142
  • 92
  • 275
  • 498

2 Answers2

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