Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if image does exists using javascript [duplicate]

Tags:

Possible Duplicate:
Check if image exists with given url using jquery
Change image source if file exists

I am throwing the value of an image path from a textbox into boxvalue and want to validate if the image exist using javascript.

 var boxvalue = $('#UrlQueueBox').val(); 

I browsed stackoverflow and found the below to get the image width/height, but don't want to use this.

var img = document.getElementById('imageid');  

How can an I validate if it is really an image from the image path?

like image 308
X10nD Avatar asked Feb 01 '13 17:02

X10nD


2 Answers

// The "callback" argument is called with either true or false // depending on whether the image at "url" exists or not. function imageExists(url, callback) {   var img = new Image();   img.onload = function() { callback(true); };   img.onerror = function() { callback(false); };   img.src = url; }  // Sample usage var imageUrl = 'http://www.google.com/images/srpr/nav_logo14.png'; imageExists(imageUrl, function(exists) {   console.log('RESULT: url=' + imageUrl + ', exists=' + exists); }); 
like image 189
maerics Avatar answered Oct 14 '22 06:10

maerics


You can create a function and check the complete property.

function ImageExists(selector) {     var imageFound = $(selector);       if (!imageFound.get(0).complete) {         return false;     }     else if (imageFound.height() === 0) {         return false;     }      return true; } 

and call this funciton

 var exists = ImageExists('#UrlQueueBox'); 

Same function with the url instead of a selector as parameter (your case):

function imageExists(url){      var image = new Image();      image.src = url;      if (!image.complete) {         return false;     }     else if (image.height === 0) {         return false;     }      return true; } 
like image 41
Felipe Oriani Avatar answered Oct 14 '22 08:10

Felipe Oriani