Google Answers Logo
View Question
 
Q: How do I determine the width and height of an image using Javascript? ( Answered 5 out of 5 stars,   0 Comments )
Question  
Subject: How do I determine the width and height of an image using Javascript?
Category: Computers > Programming
Asked by: g8z-ga
List Price: $10.00
Posted: 24 Apr 2003 09:09 PDT
Expires: 24 May 2003 09:09 PDT
Question ID: 194820
Hello,

How do I determine the width and height of an image using Javascript?

I have a loop which writes many images to the screen, but I need to
get the width and height of each image that is displayed. Since the
image names and IDs are dynamically generated, I assume that I need to
use getElementById or images[elementName] to reference the image, but
I cannot seem to get it to work.

Here's what I have so far:


for ( j = 1; j < 100; j++ )
{
	document.write( "<img id=img" + j + " name=img" + j + "
src=../images/image_" + j + ".gif>" );

	var imgWidth = document.images["img" + j].width;
	var imgHeight = document.images["img" + j].height;
	
	// do other stuff with the width and height here
}

It needs to work in Internet Explorer 5+ and Netscape 6+ on the PC and
Mac. It's ok to ignore IE 4.x and Netscape 4.x

Thanks for your help!
Darren
Answer  
Subject: Re: How do I determine the width and height of an image using Javascript?
Answered By: dogbite-ga on 24 Apr 2003 11:12 PDT
Rated:5 out of 5 stars
 
Hi g8z,

  The problem you're probably running into is that Netscape doesn't
"know" the width and height of the image right away; it has to wait a
small amount of time for the image to be loaded. IE doesn't have this
problem. For instance, with the following code (where "pic.gif" is in
the browser cache), IE gives the correct answer twice, whereas
Netscape prints zero the first time and the correct width the second
time:

  Image img = new Image();
  img.src = "pic.gif";
  alert (img.width);
  setTimeout ("alert (img.width)", 1);

A robust solution to your problem, then, is to wait until the sizes
are available by repeatedly calling setTimeout. Here's code for a
routine, called runWhenSizeAvailable, that does that for you:


  MAX_TRIES = 300; // number of times to check for the image size
before giving up
  SLEEP_TIME = 50; // number of milliseconds to sleep between size
checks

  function escapeQuotes (str) {
     return str.replace (/'/g, "\\'")
  }

  function checkSize (imgstr, code, triesRemaining) {
     eval ("img = " + imgstr);
     if (img.width != 0 && img.height != 0) { // IE doesn't do
img.complete
        paren = code.lastIndexOf (")");
        code = paren == -1 ? code + "(img.width,img.height)" :
code.slice (0, p\
aren) + ",img.width,img.height)";
        eval (code);
     } else if (triesRemaining > 0) {
        setTimeout ("checkSize('" + escapeQuots (img) + "', '" +
escapeQuotes (\
code) + "', '" + (triesRemaining - 1) + ")", SLEEP_TIME);
     }
  }

  /* Takes a string reference to an image and a string of the name of
a
   * user function (optionally with arguments) to run when the image's
size
   * is available.
   *
   * Example:
   *    runWhenSizeAvailable ("document.images[0]", "myFunc (44,
'hi')");
   * When the size of the first image in the document is available,
the
   * function "myFunc" will be called automatically as follows:
   *    myFunc (44, 'hi', width, height);
   * where width and height are the dimensions of the image. Note that
myFunc
   * is a four-argument function; the last two arguments are not
specified in
   * the "code" string when calling runWhenSizeAvailable, as they are
filled in
   * by runWhenSizeAvailable.
   */
  function runWhenSizeAvailable (img, code) {
     checkSize (img, code, MAX_TRIES);
  }

Use the above routine like this:

  function printSize (msg, width, height) {
    alert (msg + ": " + width + "x" + height);
  }

  for ( j = 1; j < n; j++ )
  {
    document.write("<img width=60 height=42 id=img" + j + " name=img"
+ j + " src=../images/image_" + j + ".jpg>" );
    runWhenSizeAvailable ("document.images['img" + j + "']",
"printSize ('size of image " + j + " is ')");
  }

I have confirmed that this works on IE 5+ and NS 6+.

  cheers,
    dogbite-ga

Clarification of Answer by dogbite-ga on 24 Apr 2003 11:34 PDT
Hi g8z,

  Because the above pasted code is rather hard to read (there are some
escape characters intermixed that are artifacts of the paste, etc.), I
put up the code on my webserver.

  You can look at the code <a
href="http://nms.lcs.mit.edu/~gch/google/images.html.txt">here</a> and
run it <a href="http://nms.lcs.mit.edu/~gch/google/images.html">here</a>.

  Cheers,
   dogbite-ga

Clarification of Answer by dogbite-ga on 24 Apr 2003 11:51 PDT
Hi Darren,

Sorry for the repeated clarifications, but I just remembered that
javascript has an "onLoad" event handler for images, which obviates
the routine I wrote for you.

You merely need to do something like this:


<script>
  function printSize (msg, img) {
    alert (msg + ": " + img.width + "x" + img.height);
  }

for ( j = 1; j < 2; j++ )
{
  document.write("<img width=60 height=42 id=img" + j + " name=img" +
j + " src=
./image_" + j + ".jpg onload='printSize (\"size of image " + j + " is
\", docume
nt.images[\"img" + j + "\"])'>");
}
</script>

You can view this in action at
http://nms.lcs.mit.edu/~gch/google/images2.html, and view the source
at http://nms.lcs.mit.edu/~gch/google/images2.html.txt

Cheers,
  dogbite

Request for Answer Clarification by g8z-ga on 27 Apr 2003 23:08 PDT
hi dogbite,

Great answer. You clearly know your javascript. Any chance that you
could answer my other question, posted at:

https://answers.google.com/answers/main?cmd=threadview&id=196259

- Darren

Clarification of Answer by dogbite-ga on 28 Apr 2003 08:52 PDT
Hey g8z-ga,

  I'm happy the answer worked out for you.

  As for your next question -- I'm not a
  Flash expert (or even much of a novice)
  so I don't know the answer to that one.

  Please let me know if you want me to answer 
  other questions in the future though.

           dogbite-ga
g8z-ga rated this answer:5 out of 5 stars

Comments  
There are no comments at this time.

Important Disclaimer: Answers and comments provided on Google Answers are general information, and are not intended to substitute for informed professional medical, psychiatric, psychological, tax, legal, investment, accounting, or other professional advice. Google does not endorse, and expressly disclaims liability for any product, manufacturer, distributor, service or service provider mentioned or any opinion expressed in answers or comments. Please read carefully the Google Answers Terms of Service.

If you feel that you have found inappropriate content, please let us know by emailing us at answers-support@google.com with the question ID listed above. Thank you.
Search Google Answers for
Google Answers  


Google Home - Answers FAQ - Terms of Service - Privacy Policy