[英]How to check whether an image is a Broken image or not in javascript
我從 Twitter 獲取個人資料圖片並將圖片網址存儲在我的數據庫中。 一些 url 給出了損壞的圖像,其中 url 以圖像擴展名結尾,任何人都可以幫助我檢查圖像是有效圖像還是損壞圖像。 如果存在損壞的圖像,我需要顯示默認圖像..
var image = opinionmakers[i].user_image;
if (type == 'Twitter' && image.match(/jpeg/)) {
img = image.slice(0, -12) + ".jpeg";
} else if (type == 'Twitter' && image.match(/jpg/)) {
img = image.slice(0, -11) + ".jpg";
} else if (type == 'Twitter' && image.match(/JPG/)) {
img = image.slice(0, -11) + ".JPG";
} else if (type == 'Twitter' && image.match(/png/)) {
img = image.slice(0, -11) + ".png";
} else if (type == 'Twitter' && image.match(/gif/)) {
img = image.slice(0, -11) + ".gif";
} else {
img = image;
}
首先,為了檢查正確的圖像擴展名,我建議像這樣使用 regex.test 函數
/\.(jpeg|jpg|png|gif)\b/i.test(url);
這意味着“匹配所有帶有 '.' 的模式。 后跟 () 中的任何字符串,/b 表示詞尾,/i 表示不區分大小寫。您也可以在其余代碼之前使用它一次,以使其更清晰。
要檢查有效圖像,您可以創建一個 img 元素並對其錯誤和加載回調做出反應,例如https://jsfiddle.net/msong1q2/1/
var IsValidImage = function (url, callback) {
$("<img>", {
src: url,
error: function () {
callback(url, false);
},
load: function () {
callback(url, true);
}
});
}
var CallbackFunction = function (url, isValid) {
if (isValid) {
alert(url + ' is valid image');
//do whatever logic you want
} else {
alert(url + ' is invalid image');
//do whatever logic you want
}
}
IsValidImage('http://nonextistentUrl.com/image.png', CallbackFunction);
IsValidImage('http://placehold.it/350x150.png', CallbackFunction);
只是一個小的小提琴如何如何可以這樣實現:
<img src="https://pbs.twimg.com/profile_images/596630109613740032/S_jtpvR4.jpg"
onLoad="checkState(this, true);" onError="checkState(this, false);">
<img src="https://www.google.de/images/nav_logo195.png"
onLoad="checkState(this, true);" onError="checkState(this, false);">
...
function checkState(e, s)
{
console.log("loaded:");
console.log(s);
console.log(e);
}
有兩種相對較好的方法可以檢查圖像是否在您離開的位置。
A. 你只想檢查一個圖像(跨域能力)是否可用,不要顯示它
它是純 javascript,因此它可以在大多數移動/桌面瀏覽器上本地運行。 這段代碼也避免了無用的全圖加載。
此代碼在控制台中引發錯誤。 但這不是問題。使用try catch
可能可以避免該錯誤,但這需要在函數內部使用匿名函數,如果大量使用會導致內存泄漏。 ;) 。 所以 404 錯誤不是問題,因為它實際上沒有找到請求的圖像。
var c=new XMLHttpRequest;
c.open('GET','THE_IMAGE_LINK');
c.onreadystatechange=function(){
if(this.readyState==2){
// get only the header info not the full image
alert(this.status);
// 200=img ok 404=not found
this.status!='200'||alert(this.getAllResponseHeaders());
//contains more info about the image
this.abort()
//stop loading the extra image data if you just check.
}
};
c.send();
0:請求未初始化
1:服務器連接建立
2:收到請求
3:處理請求<-不需要
4:請求已完成且響應已准備好 <- 不需要
B. 如果找不到,您想顯示替代圖像。
function noimg(e){
this.src='NoImgIcon.png';
}
function fadein(e){
document.body.appendChild(this);
}
function loadIMG(url){
var img=document.createElement('img');
img.onload=fadein;
img.onerror=noimg;
img.src=url
}
loadIMG('THE_IMAGE_LINK');
想要它在一個函數中? 問。 如果你有問題,就問吧。
只需檢查圖像是否完整。 這是最簡單的方法,對我有用。
if(image.complete){
//draw image
}
更多信息: https : //www.w3schools.com/jsref/dom_obj_image.asp
complete : 返回瀏覽器是否完成加載圖像
注意:當您有一個每秒多次重繪圖像的循環時,這最有用,並且可能會在加載圖像之前嘗試繪制它。 如果你只需要在它加載后繪制一次,那么onload
處理程序應該是onload
的方法,就像這個問題的其他答案所推薦的那樣。
<!DOCTYPE html>
<html>
<head>
<script>
function imageCheck(event) {
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.onload = function () {
if (reader.result == 'data:') {
alert('This file is corrupt')
} else {
alert('This file can be uploaded')
}
}
reader.readAsDataURL(event.target.files[0]);
}
</script>
</head>
<body>
<input type='file' id="image" onchange="imageCheck(event)">
<img id="output_image" />
</body>
</html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.