如何检测图像路径是否有效?

时间:2013-05-02 17:48:10

标签: javascript image

我找到了一个关于图像的问题

How to detect if the image path is broken?

我尝试过以下代码

var image = new Image;
    image.src = "http://project" + path + '.png';

    image.onload = function(){
        var imageWidth = this.width + this.height;
        if(imageWidth==0){
           image.src = "http://project2" + path + '.png';            

           //the project2 path could be broken too and 
           //I want to use project3 or project4 as the
           //path and keep testing it, but there is no way to do it from here.
       }
    }

可以在这里进行recursive测试吗?非常感谢!

2 个答案:

答案 0 :(得分:3)

您可以尝试以下设置:

var paths = ["/img1", "/img2", "/img3"];
var beginning = "http://project";
var ending = ".png";

function getImage(images, prefix, suffix, callback) {
    var iterator = function (i) {
        if (i < images.length) {
            var image = new Image();

            image.onload = function () {
                var imageWidth = this.width + this.height;
                if (imageWidth === 0) {
                    console.log("onload problem");
                    iterator(++i);
                } else {
                    console.log("onload good");
                    callback(i, image);
                }
            };

            image.onerror = function () {
                console.log("onerror");
                iterator(++i);
            };

            image.src = prefix + images[i] + suffix;
        }
    };
    iterator(0);
}

getImage(paths, beginning, ending, function (index, img) {
    console.log("Callback: ", index, ", ", img);
});

DEMO: http://jsfiddle.net/2mRMr/2/

答案 1 :(得分:1)

图像损坏会调用onerror,而不是onload

image.onerror = function () {
  console.log("broken");
  callToTryNewSrc();
}

基本递归检查

function getImage(path, callback) {

    //if numeric
    var ind = 1;
    var maxServer = 5;

   //if named differently
   //var ind = 0;
   //var servers = ["//foo1","//foo2","//bar1"];
   //var maxServer = servers.length-1;


    function test() {

        var img = new Image();
        img.onload = function () {
            if (callback) {
                callback(img);
            }
        }
        img.onerror = function () {
            if (ind <= maxServer) {
                test();
            } else {
                if (callback) {
                    callback(img);
                }
            }
        }
        var currentPath = "http://project" + ind + path + '.png';
        //var currentPath = servers[ind] + path + '.png';

        img.src = currentPath;
        ind++;
    }

    test();

}

//calling it
getImage("/foo", function (img) {
    console.log(img);
});