如何在javascript中检查图像是否是损坏的图像 [英] How to check whether an image is a Broken image or not in javascript

查看:64
本文介绍了如何在javascript中检查图像是否是损坏的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从 Twitter 获取个人资料图片并将图片网址存储在我的数据库中.一些 url 给出了损坏的图像,其中 url 以图像扩展名结尾,任何人都可以帮助我检查图像是有效图像还是损坏图像.如果存在损坏的图像,我需要显示默认图像..

I get a profile image from Twitter and store the image url in my database. some url gives broken image where the url ends with image extension and can anyone help me to check the image is a valid image or broken image. if broken image exists, i need to display a default image..

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 函数

First, for checking the right image extension I would suggest to use regex.test function like this

/\.(jpeg|jpg|png|gif)\b/i.test(url);

这意味着匹配所有带有'.'的模式后跟 () 中的任何字符串,/b 表示词尾,/i 表示不区分大小写.您也可以在其余代码之前使用它一次,以使其更清晰.

That means "match all patterns that have a '.' followed by any of those strings in (), /b meaning end of word and /i meaning case in-sensitive. You can also use it just once, before the rest of your code to make it cleaner.

要检查有效图像,您可以创建一个 img 元素并对其错误和加载回调做出反应,例如 https://jsfiddle.net/msong1q2/1/

To check an valid image you can create an img element and react on its error and load callbacks, like this 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);

这篇关于如何在javascript中检查图像是否是损坏的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆