验证图像URL

Validate Image URL

本文关键字:URL 图像 验证      更新时间:2023-09-26

我有一个图像URL(http://t2.gstatic.com/images?q=tbn:ANd9GcTR_RHZrrb25Cx1qGPul6PYsCnVsIqtRuJxRS1Bj0I8DPXqQx-zow)。我想在JavaScript中验证这一点,无论图像是否存在。请帮我找到解决办法。

try {
var img = document.createElement("img");
img.src ="http://t2.gstatic.com/images?q=tbn:ANd9GcTR_RHZrrb25Cx1qGPul6PYsCnVsIqtRuJxRS1Bj0I8DPXqQx-zowsd";
} catch(err)
{
    //
}
if(img.height > 0) {
 //image exists
} else {
 // image not exists
}

您可以在隐藏的div中加载图像,并检查图像是否已加载。我建议您使用jQuery来实现这一点。

加载事件的进一步阅读:http://api.jquery.com/load-event/

HTML:

<div id="image-container" style="display: none">
    <img src="http://your/image/url">
</div>

Javascript/jQuery代码:

    $('img', '#image-container ').load(function() {
        // image loaded
    });

如果文件存在,您的帖子几乎与更改图片来源相同,该文件以前是由anotherhrubery发布的。

你可以试试这个

<img src="http://mydomain.com/images/image1.jpg" onerror="this.src='http://mydomain2.com/images/image1.jpg'" />

或者

<script language="JavaScript"><!-
function testImage(URL) {
var tester=new Image();
tester.onLoad=isGood;
tester.onError=isBad;
tester.src=URL;
}
function isGood() {
alert('That image exists!');
}
function isBad() {
alert('That image does no exist!');
}
//--></script>