如何检查一个图像是否是一个破碎的图像或不是在javascript

How to check whether an image is a Broken image or not in javascript

本文关键字:图像 一个 javascript 破碎 何检查 是否是 检查      更新时间:2023-09-26

我从Twitter获取个人资料图像并将图像url存储在数据库中。一些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;
                }

这只是一个如何实现的小技巧:

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

首先,为了检查正确的图像扩展,我建议使用regex。像这样测试函数

/'.(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);

有两种相对较好的方法来检查图像是否在您留下它的地方。

  1. 使用图像属性onerror(兼容所有浏览器)。
  2. 使用ajax(需要兼容性,在控制台中抛出和错误,跨域策略等)。

。你只想检查一个图像(跨域能力)是否可用,不要显示它

这是纯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: server connection established

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

想在函数中使用它吗?问。

<!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>

检查图片是否完整。这是最简单的方法,对我来说很有效。

if(image.complete){
   //draw image
}

更多信息:https://www.w3schools.com/jsref/dom_obj_image.asp

complete:返回浏览器是否完成图片加载

注意:当你有一个每秒重画图像多次的循环,并且可能在加载图像之前尝试画它时,这是最有用的。如果您只需要在它加载后绘制一次,那么onload处理程序应该是一种方法,就像这个问题的其他答案所推荐的那样。