5

I'm appending an image in my JavaScript code but want to get its correct width and height. Is this possible? My code looks like this:

$('body').append('<img src="path.jpg" width="'
        + w + '" height="' + h + '" alt="" />');

I know how to get the image width after it has been loaded but I'm loading an img and want to get its corresponding width and height directly. Any tips?

Peter O.
  • 32,158
  • 14
  • 82
  • 96
adnan
  • 1,385
  • 2
  • 17
  • 31

5 Answers5

2

You can get the image's sizes after loading it:

var imageWidth;
var imageHeight;
$('<img>').on('load', function(){ 
    imageWidth = this.width; 
    imageHeight = this.height; 
    $('body').append($(this));
}).attr('src', imageUrl);
gabitzish
  • 9,535
  • 7
  • 44
  • 65
1

The HTML spec recommends to specify height and width for <img> as a hint for a visual agent, which mixes the markup and the style rules to build a visual representation of a HTML document. In the CSS box model, the image dimensions are intrinsic, ie they are implicit in the binary blob. This means that a browser has to wait a HTTP response before deciding how big the image is and thus how to lay out and position siblings and parents. Specifying the dimensions in the HTML pages helps the browser to quickly render the page, because it can assign width and height before downloading the image from the server.

At this point it should be clear that there can be no way to access the image width on the client before downloading it. When the Javascript knows it, the browser already knew, and you state it's too late for your requirements.

So the only option to hint the browser is measuring the image on the server side. It can be done on a per-request basis (but it's a waste of resources), or it can be done once when the image is first uploaded (and then retrieved from a database), or eventually it can be assumed constant, for example if it's a profile picture that your service will always grow or shrink to be exactly W x H pixels big (this could be a configuration parameter).

Raffaele
  • 20,627
  • 6
  • 47
  • 86
  • Thanks, I was afraid this was the problem. So one option that is left is to preload the image in the cache but make it invisible and then show it? I think i'll just give parameters when uploading the image, that seems better then preloading images. – adnan Dec 07 '12 at 23:55
  • If you make it invisible while it's not loaded, there's no point in settings the dimensions, because the browser must relayout anyway. The only option is measuring on the server, however note that this is not a requirement and is not common practice. If you really really want to, that's ok, otherwise just skip it – Raffaele Dec 08 '12 at 09:02
  • Thanks, that would like something like: http://stackoverflow.com/questions/1944280/determine-original-size-of-image-cross-browser . But I'm now going to add parameters to the uploaded file automatically when it's uploaded – adnan Dec 08 '12 at 09:46
0
var image = new Image;
image.src = $('img').prop('src');
alert($(image).prop('height'))
raam86
  • 6,785
  • 2
  • 31
  • 46
0

You can load the image ahead of time without necessarily having to display it immediately.

var img = document.createElement('img');
img.src = 'your_image.jpg';
var imgHeight = img.height,
    imgWidth = img.width;

You can now call it along with the correct details, whenever you require.

MCM
  • 74
  • 5
  • You do have to wait until the image is loaded to get it's sizes. Your code won't work for images that load slow. – gabitzish Dec 08 '12 at 08:48
0

I decided to create a new function in wordpress that outputs the image dimensions so I can retrieve does with wordpress

function wpsc_the_product_dimensions( $width='', $height='', $product_id='' ) {
    if ( empty( $product_id ) )
        $product_id = get_the_ID();


    $product = get_post( $product_id );

    if ( $product->post_parent > 0 )
        $product_id = $product->post_parent;

    $attached_images = (array)get_posts( array(
                'post_type' => 'attachment',
                'numberposts' => 1,
                'post_status' => null,
                'post_parent' => $product_id,
                'orderby' => 'menu_order',
                'order' => 'ASC'
            ) );


    $post_thumbnail_id = get_post_thumbnail_id( $product_id );

    $image_attributes = wp_get_attachment_image_src( $post_thumbnail_id, 'large' );

    $image_dimensions = 'product-link="'.$image_attributes[0].'" product-width="'.$image_attributes[1].'" product-height="'.$image_attributes[2].'"';

    return $image_dimensions;
}

and attach the image_dimensions to the img and retrieve does with javascript

w = $(this).attr('product-width');
h = $(this).attr('product-height');
adnan
  • 1,385
  • 2
  • 17
  • 31