Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery/javascript - Get Image size before load

I have a list of images that is rendered as thumbnails after upload. The issue that I have is I need the dimensions of the fully uploaded images, so that I can run a resize function if sized incorrectly.

Function that builds the image list

function buildEditList(json, galleryID)
{
    //Hide the list
    $sortable = $('#sortable');
    $sortable.hide();

    for(i = 0, j = json.revision_images.length; i < j; i++) {
        $sortable.append(
            "<li id='image_" + json.revision_images[i].id + "'><a class=\"ui-lightbox\" href=\"../data/gallery/"
            + galleryID
            + "/images/album/"
            + json.revision_images[i].OrgImageName
            + "\"><img id=\""
            + json.revision_images[i].id
            + "\" alt=\"\" src=\"../data/gallery/"
            + galleryID 
            + "/images/album/" 
            + json.revision_images[i].OrgImageName 
            + "\"/></a></li>"
        ).hide();
    }
    //Set first and last li to 50% so that it fits the format
    $('#sortable li img').first().css('width','50%');
    $('#sortable li img').last().css('width', '50%');

    //Fade images back in 
    $sortable.fadeIn("fast",function(){
        var img = $("#703504"); // Get my img elem -- hard coded at the moment
        var pic_real_width, pic_real_height;
        $("<img/>") // Make in memory copy of image to avoid css issues
            .attr("src", $(img).attr("src"))
            .load(function() {
                pic_real_width = this.width;   // Note: $(this).width() will not
                pic_real_height = this.height; // work for in memory images.
        });
        alert(pic_real_height);
    });

}

I have been trying to use the solution from this stackoverflow post, but have yet to get it to work, or it may just be my code. if you have any ideas on this I could use the help. Currently the alert is coming back undefined.

like image 642
SuperNinja Avatar asked Nov 04 '22 08:11

SuperNinja


1 Answers

There's a newer js method called naturalHeight or naturalWidth that will return the information you're looking for. Unfortunately it wont work in older IE versions. Here's a function I created a few months back that may work for you. I added a bit of your code below it for an example:

function getNatural($mainImage) {
    var mainImage = $mainImage[0],
        d = {};

    if (mainImage.naturalWidth === undefined) {
        var i = new Image();
        i.src = mainImage.src;
        d.oWidth = i.width;
        d.oHeight = i.height;
    } else {
        d.oWidth = mainImage.naturalWidth;
        d.oHeight = mainImage.naturalHeight;
    }
    return d;
}

var img = $("#703504");
var naturalDimension = getNatural(img);
alert(naturalDimension.oWidth, naturalDimension.oHeight)​
like image 76
Syon Avatar answered Nov 08 '22 10:11

Syon