0

我发现了一个关于图像的问题

如何检测图像路径是否损坏?

我尝试了以下代码

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测试吗?非常感谢!

4

2 回答 2

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);
});

演示:http: //jsfiddle.net/2mRMr/2/

于 2013-05-02T18:05:26.157 回答
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);
});
于 2013-05-02T17:50:27.457 回答