Getting image width on image load fails on IE
Asked Answered
S

8

12

I have a image resizer function that resize images proportional. On every image load a call this function with image and resize if its width or height is bigger than my max width and max height. I can get img.width and img.height in FF Chrome Opera Safari but IE fails. How can i handle this?

Let me explain with a piece of code.

<img src="images/img01.png" onload="window.onImageLoad(this, 120, 120)" />

function onImageLoad(img, maxWidth, maxHeight) {
     var width = img.width; // Problem is in here
     var height = img.height // Problem is in here
}

In my highligted lines img.width don't work on IE series.

Any suggestion?

Thanks.

Spiel answered 17/12, 2010 at 15:39 Comment(5)
Have you tried img.currentStyle.width ??Rosalba
@Fatih Suggestion: don't mix JavaScript in your HTML like that (the onload attribute). Dynamically attach event handlers in JS alone.Jeuz
Works fine in IE 8 over here: jsbin.com/ehovu4/#noeditKenward
I have find the problem. Stupid IE cannnot calculate display: none; image's width and height. I have set images visibility: hidden; then everything worked but until images load horizontal and vertical scroll bars is seeing.Spiel
+1 for the display:none hintSilures
A
22

Don't use width and height. Use naturalWidth and naturalHeight instead. These provide the image unscaled pixel dimensions from the image file and will work across browsers.

Amphibology answered 25/7, 2013 at 13:57 Comment(2)
IMHO, This is the best answer on the page and should be the accepted answer.Calumet
In IE 8, you can get the natural width by creating an Image instance, setting the src to the desired image, and grabbing that instance's dimensions: function onImageLoad(img, maxWidth, maxHeight) { var ghost = new Image(); ghost.src = img.src; var width = ghost.width; var height = ghost.height ... }Amidships
R
4

Man, I was looking for this for 2 days. Thanks.

I'm using jQuery, but it doesnt matter. Problem is related to javascript in IE.

My previous code:

var parentItem = $('<div/>')
   .hide();      // sets display to 'none'

var childImage = $('<img/>')
   .attr("src", src)
   .appendTo(parentItem)   // sets parent to image
   .load(function(){
      alert(this.width);  // at this point image is not displayed, because parents display parameter is set to 'none' - IE gives you value '0'
   });

This is working in FF, Opera and Safari but no IE. I was getting '0' in IE.

Workaround for me:

var parentItem = $('<div/>')
   .hide();

var childImage = $('<img/>')
   .attr("src", src)
   .load(function(){
      alert(this.width);  // at this point image css display is NOT 'none'  - IE gives you correct value
      childImage.appendTo(parentItem);   // sets parent to image
   });
Riarial answered 18/7, 2011 at 14:32 Comment(0)
D
3

This is how I solved it (because it's the only js on the site I didn't want to use a library).

    var imageElement = document.createElement('img');
    imageElement.src = el.href; // taken from a link cuz I want it to work even with no script
    imageElement.style.display      = 'none';

    var imageLoader = new Image();
    imageLoader.src = el.href;
    imageLoader.onload = function() {
        loaderElement.parentElement.removeChild(loaderElement);
        imageElement.style.position     = 'absolute';
        imageElement.style.top          = '50%';
        imageElement.style.left         = '50%';
        // here using the imageLoaders size instead of the imageElement..
        imageElement.style.marginTop    = '-' + (parseInt(imageLoader.height) / 2) + 'px';
        imageElement.style.marginLeft   = '-' + (parseInt(imageLoader.width) / 2) + 'px';
        imageElement.style.display      = 'block';
    }
Density answered 26/11, 2012 at 18:23 Comment(0)
S
2

It's because IE can't calculate width and height of display: none images. Use visibility: hidden instead.

Spiel answered 27/11, 2012 at 9:38 Comment(1)
FYI, the working sample/failed sample links result in HTTP 404 errors.Cupreous
E
1

Try

 function onImageLoad(img, maxWidth, maxHeight) {
   var width = img.width; // Problem is in here
   var height = img.height // Problem is in here
   if (height==0  && img.complete){
       setTimeOut(function(){onImageLoad(img, maxWidth, maxHeight);},50);
   }

 }
Elul answered 23/4, 2016 at 21:24 Comment(0)
P
0
    var screenW = screen.width;
    var screenH = screen.height;
    //alert( screenW );
    function checkFotoWidth( img, maxw )
    {
        if( maxw==undefined)
            maxw = 200;
        var imgW = GetImageWidth(img.src);
        var imgH = GetImageHeight(img.src);
            //alert(GetImageWidth(img.src).toString()); // img.width); // objToString(img));
        if (imgW > maxw || (img.style.cursor == "hand" && imgW == maxw))
        {
            if (imgW > screenW) winW = screenW;
            else winW = imgW;

            if (imgH > screenH) winH = screenH;
            else winH = imgH;

            img.width=maxw;
            img.style.cursor = "pointer";

            img.WinW = winW;
            img.WinH = winH;
            //alert("winW : " + img.WinW);
            img.onclick = function() { openCenteredWindow("Dialogs/ZoomWin.aspx?img=" + this.src, this.WinW, this.WinH, '', 'resizable=1'); }
            img.alt = "Klik voor een uitvergroting :: click to enlarge :: klicken Sie um das Bild zu vergrössern";
            //alert("adding onclick);
        }
    }

    function GetImageWidth(imgSrc) 
    {
        var img = new Image();
        img.src = imgSrc;
        return img.width;
    } 

    function GetImageHeight(imgSrc) 
    {
        var img = new Image();
        img.src = imgSrc;
        return img.height;
    } 
Phyllis answered 17/12, 2010 at 15:43 Comment(1)
it's also best to first hide your image, then display it once you resized it. Otherwise you'll get flickering effects with large images.Phyllis
R
0

I'd try this:

function onImageLoad(img, maxWidth, maxHeight) {
   var width, height;
   if ('currentStyle' in img) {
     width = img.currentStyle.width;
     height = img.currentStyle.height;
   }
   else {
     width = img.width;
     height = img.height;
   }
   // whatever
}

edit — and apparently if I were to try that I'd learn it doesn't work :-) OK, well "width" and "height" definitely seem to be attributes of <img> elements as far as IE is concerned. Maybe the problem is that the "load" event is firing for the element at the wrong time. To check whether that's the case, I would then try this:

function onImageLoad(img, maxWidth, maxHeight) {
   var width, height;
   var i = new Image();
   i.onload = function() {
     width = i.width; height = i.height;
     // ... stuff you want to do ...
   };
   i.src = img.href;
}
Rosalba answered 17/12, 2010 at 16:4 Comment(7)
it returns "auto". But I need the exact width and height, I mean the dimensionsSpiel
Oh crap :-) Well, that's IE for you. Let me think about it for a sec.Rosalba
How about offsetWidth/offsetHeight? I suspect those will work even with width/height return auto.Jeuz
@Jeuz offsetWidth/offsetHeight returns 0Spiel
@Fatih That seems very broken then. Are the images surely loaded? I would personally hack it by adding a setTimeout(...,1) kicked off from the load event to give it one more chance to re-layout the page before asking for the dimensions.Jeuz
We can be sure images are loaded if IE doesn't lie to us because the function is calling on image load. I guess, I have done with it. check the question's third comment that was written by me.Spiel
problem is setting the images display: none; IE cannot calculate the displayed none image's dimensionsSpiel
J
-1
getDisplay().getImage().setUrl(imgURL);
final Image img = new Image(imgURL);
int w=img.getWidth();
int h=img.getHeight();
Justinajustine answered 23/7, 2014 at 13:57 Comment(1)
The question is about JavaScriptDardan

© 2022 - 2024 — McMap. All rights reserved.