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.

5
  • Have you tried img.currentStyle.width ?? Commented Dec 17, 2010 at 16:02
  • @Fatih Suggestion: don't mix JavaScript in your HTML like that (the onload attribute). Dynamically attach event handlers in JS alone. Commented Dec 17, 2010 at 16:22
  • Works fine in IE 8 over here: jsbin.com/ehovu4/#noedit Commented Dec 17, 2010 at 16:50
  • 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. Commented Dec 17, 2010 at 22:10
  • +1 for the display:none hint Commented Oct 29, 2012 at 2:18

8 Answers 8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

IMHO, This is the best answer on the page and should be the accepted answer.
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 ... }
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
   });

Comments

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

Comments

2

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

1 Comment

FYI, the working sample/failed sample links result in HTTP 404 errors.
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);
   }

 }

Comments

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

1 Comment

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

7 Comments

it returns "auto". But I need the exact width and height, I mean the dimensions
Oh crap :-) Well, that's IE for you. Let me think about it for a sec.
How about offsetWidth/offsetHeight? I suspect those will work even with width/height return auto.
@Phrogz offsetWidth/offsetHeight returns 0
@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.
|
-1
getDisplay().getImage().setUrl(imgURL);
final Image img = new Image(imgURL);
int w=img.getWidth();
int h=img.getHeight();

1 Comment

The question is about JavaScript

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.