Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
                }
like image 322
Manoj Kumar Avatar asked Mar 16 '23 01:03

Manoj Kumar


2 Answers

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

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.

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);
like image 80
mcs_dodo Avatar answered Mar 30 '23 00:03

mcs_dodo


Just a small fiddle to how how this could be achieved:

    <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);
}
like image 33
Axel Amthor Avatar answered Mar 30 '23 00:03

Axel Amthor