如何检测图像路径是否有效
How to detect if the image path is valid?
我发现了一个关于图像的问题
如何检测图像路径是否被破坏?
我尝试了以下代码
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
测试吗?非常感谢!
您可以尝试以下设置:
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/
破碎图像将调用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);
});
相关文章:
- 复制图像路径以单击它
- 如何使用jquery将base64图像路径转换为真实路径
- 滚动页面时的弯曲图像路径
- Gulp bower图像路径
- Symfony2-Javascript文件中的图像路径
- 将图像内容而非图像路径存储在mongodb中
- MVC5 和 Javascript 相对图像路径混淆
- 简单的图像滑块Javascript图像路径在IE 6中不起作用
- 从表单中派生要使用javascript对象加载的图像路径
- 如何设置与CKEditor一起使用的图像路径
- AngularJS/JavasScript中的本地图像路径
- 将 grunt-usemin 与动态生成的图像路径一起使用
- 如何使用 php 将捕获的图像路径存储在 mysql 数据库中
- 需要 Rails 应用程序中本机 HTML 的图像路径
- Javascript 无法解析正确的图像路径,当使用 URL 路由在 ASP.Net 中请求页面时
- 在 jquery 中为内联 css 构建图像路径的最佳方法
- “电子邮件”在电话间隙中共享的图像路径
- 使用带有错误图像路径的 jQuery 加载打开的页面
- 推送整个网站数组中的所有图像路径
- 使用一个javascript字符串作为css背景属性的图像路径