1

I'm receiving images inside a long string from a server using an ajax call

The url of the image is inside result[1] for sure. I've used width/naturalWidth and height/naturalHeight and on occasion they return 0 and in other cases they return the right size in pixels

var imgElement = jQuery("<img>").attr("src", result[1]);
var width = imgElement[0].naturalWidth;
var height = imgElement[0].naturalHeight;
if (width >= that.minImgPixels && height >= that.minImgPixels) {
    image = result[1];
}

How is the right way to check image width and height without inserting it to the dom?

CodingIntrigue
  • 75,930
  • 30
  • 170
  • 176
Alon
  • 3,734
  • 10
  • 45
  • 64
  • This answer to a similar question shows you how to progamatically create the image in javascript without it having to be in the dom first: http://stackoverflow.com/a/626505/1805956 – Alex Woodhead Sep 10 '13 at 07:35

2 Answers2

0

The problem occures since settings the src of an jQuery("<img>")takes time and while it does that, the javascript continues to run to the next lines which produce 0 since the image wasn't loaded yet.

The solution is to set a load event like that:

var imgElement = jQuery("<img>").load(function(){
    var width = imgElement[0].naturalWidth;
    var height = imgElement[0].naturalHeight;
    if (width >= that.minImgPixels && height >= that.minImgPixels) {
        image = result[1];
    }
}).attr("src", result[1]);
Alon
  • 3,734
  • 10
  • 45
  • 64
  • see load method caveats at [http://api.jquery.com/load-event/](http://api.jquery.com/load-event/) – Joe Sep 10 '13 at 07:37
0

try this:

function GetAnImage(src) {

    var newImg = document.createElement('img');
    newImg.src = src;

    return newImg;
}

var newImg = GetAnImage("abc.jpg");
newImg.onload = function () {                           
    var height = this.height;
    var width = this.width;  
    //do with the image as you want         
}

or see this link: Getting auto size of IMG before adding it to DOM (Using JQuery)

Community
  • 1
  • 1
maverickosama92
  • 2,685
  • 2
  • 21
  • 35