Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load image if found, else load another image

what I need to do is simple to say but (for me) hard to do:

using javascript, given an image name, ie "image01.jpg", I need to check if this image exists in a certain folder or path (local or on the web). If the image does not exist under that folder, I need to check if the same image exists in another folder.

for example, with pseudo code

imageToFind = 'image01.jpg'
path1 = 'users/john/images'
path2 = 'users/mike/img'

if path1+'/'+imageToFind exists
    //do something
else
    if path2+'/'+imageToFind exists
        //do something
    else
        print('NOT FOUND')

what kind of approach do you suggest? I tryed to achieve this using ajax first, and then using javascript's Image() , but I failed in both these cases.

Thanks in advance for any help, best regards

like image 302
BeNdErR Avatar asked Oct 29 '12 17:10

BeNdErR


3 Answers

Use the onerror callback :

var img = new Image();
img.onerror = function(){
   img = new Image(); // clean the error (depends on the browser)
   img.onerror = function(){
       console.log('not found at all !');
   };
   img.src = path2+'/'+imageToFind;
};
img.src = path1+'/'+imageToFind;
like image 181
Denys Séguret Avatar answered Nov 06 '22 12:11

Denys Séguret


You can pretty much rely on native onload and onerror event handlers which fire for Image nodes. So it could look like

var images = ['users/john/images/image01.jpg','users/mike/img/image01.jpg','some/more/path/image01.jpg'];

(function _load( img ) {
    var loadImage = new Image();

    loadImage.onerror = function() {
        // image could not get loaded, try next one in list
        _load( images.shift() );
    };
    loadImage.onload = function() {
        // this image was loaded successfully, do something with it
    };

    loadImage.src = img;
}( images.shift() ));

This code probably does a little more than you actually asked for. You can basically but as much image paths as you wish into that array, the script will search the list until it could load one image successfully.

like image 31
jAndy Avatar answered Nov 06 '22 13:11

jAndy


try something like

objImg = new Image();
objImg.src = 'photo.gif';

if(!objImg.complete)
 { 
      img.src = path2+'/'+imageToFind; //load other image
  }else{
     img.src = path1+'/'+imageToFind;
  }
like image 1
NullPoiиteя Avatar answered Nov 06 '22 14:11

NullPoiиteя