【问题标题】:How to check whether an image is a Broken image or not in javascript如何在javascript中检查图像是否是损坏的图像
【发布时间】:2015-05-16 07:23:43
【问题描述】:

我从 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;
                }

【问题讨论】:

标签: javascript jquery


【解决方案1】:

首先,为了检查正确的图像扩展名,我建议使用像这样的 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);

【讨论】:

  • 正则表达式不是一个好主意,因为您可以使用服务器端脚本来生成图形或服务器重定向(漂亮的 url)。图像事件是检测损坏图像或服务器端代码的唯一可靠方法,该代码将获取图像并检查 mime 类型,或者仅当它不是 404 时。
  • 同意,在检查有效性时没有用。我改变了措辞,所以答案更清楚了。
【解决方案2】:

只是一个小小的fiddle 来了解如何实现这一点:

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

【讨论】:

    【解决方案3】:

    有 2 种比较好的方法可以检查图像是否在您离开的位置。

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

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

    想要在函数中使用它吗?问。如果您有任何问题,请尽管提问。

    【讨论】:

      【解决方案4】:

      只需检查图像是否完整。这是最简单的方法,对我有用。

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

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

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

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

      【讨论】:

        【解决方案5】:
        <!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>
        

        【讨论】:

        • 这样在上传之前我们可以使用java脚本检查图片是否损坏。
        猜你喜欢
        • 1970-01-01
        • 2012-08-31
        • 2021-07-28
        • 2012-04-13
        • 2012-10-20
        • 1970-01-01
        • 2013-04-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多