Manoj Kumar
Manoj Kumar

Reputation: 107

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

Upvotes: 9

Views: 25612

Answers (5)

Rocky
Rocky

Reputation: 11

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

Upvotes: 1

shieldgenerator7
shieldgenerator7

Reputation: 1756

Just check if the image is complete or not. It's the simplest way and it worked for me.

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

More info: https://www.w3schools.com/jsref/dom_obj_image.asp

complete: Returns whether or not the browser is finished loading an image

Note: This is most useful when you have a loop that is redrawing the image multiple times a second and could potentially try to draw it before the image is loaded. If you only have to draw it once after it loads, then the onload handler should be the way to go, like the other answers to this question recommend.

Upvotes: 1

mcs_dodo
mcs_dodo

Reputation: 738

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

Upvotes: 3

cocco
cocco

Reputation: 16716

There are 2 relatively good ways to check if an image is where you left it.

  1. using the image attribute onerror (compatible with all browsers).
  2. using ajax (needs compatibility, throws and error in the console,crossdomain policy and more).

A. You only want to check if an image (crossdomain capable) is aviable and DON'T DISPLAY it

It's pure javascript so it works natively on most mobile/desktop browsers. This code also avoids the useless load of the full image.

This code throws an error in the console. but that's not a problem.it's probably possible to avoid that error by using try catch but that needs a anonymous function inside a function whitch will lead to memory leaking if used heavily. ;) . So a 404 error is not a problem as it actually didn't find the requested image.

 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: request not initialized

1: server connection established

2: request received

3: processing request <- not needed

4: request finished and response is ready <- not needed

B. You want to DISPLAY an alternative image if you cant find it.

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

Want it in a function? ask. If you have any questions just ask.

Upvotes: 2

Axel Amthor
Axel Amthor

Reputation: 11106

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

Upvotes: 5

Related Questions