2013-05-02 70 views
0

我發現關於如何檢測圖像路徑是否有效?

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測試圖像的問題嗎?非常感謝!

+0

簡單地打開開發人員工具並查看您的任何鏈接是否損壞是不夠的? – blackhawk 2013-05-02 17:54:04

+0

我需要在飛行中做到這一點。所以代碼可以選擇具有有效路徑的圖像。 – FlyingCat 2013-05-02 17:54:31

回答

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

破碎的圖像將叫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); 
}); 
+0

爲什麼要投票? – Gary 2013-05-02 17:52:25

+1

因爲我很棒? – epascarello 2013-05-02 17:52:50

+0

我投了票,因爲你是令人敬畏的epascarello。 – FlyingCat 2013-05-02 17:55:07