gremo
gremo

Reputation: 48487

Getting original image for cropping, ignoring the width attribute?

My user can upload really big images, and for cropping and display purposes i'm adding width attribute so it will fit well in the browser window. Real image size can be - say 1920 x 1080 px.

<!-- width added for display purpose -->
<img class="croppable" src="images/fhd.jpg" width="640" />

In order to calculate real selection box dimension (if the x coordinate is 20px then would be 60px in the original full hd picture) i need to get the full image size before apply the width attribute.

The problem is that this will return 640 as value, taking into account the width attribute:

// Important: Use load event to avoid problems with webkit browser like safari
// when using cached images
$(window).load(function(){
    $('img.croppable').each(function(){
        alert(this.width);
    });
});

Please don't flag this as duplicate since what i'm asking is completly different from simple image width/height retrival (which works, actually).

EDIT: Chris G. solution seems not working:

$(window).load(function(){
    $('img.croppable').each(function(){
        console.log(this.src);
        var original = new Image(this.src);
        console.log(original);
        $("#original_w").text(original.width); // Temp, more images to be added
        $("#original_h").text(original.height); // Temp, more images to be added
    });
});

Console output:

http://localhost/DigitLifeAdminExtension/images/pillars-of-creation.jpg
<img width="0">

Upvotes: 0

Views: 562

Answers (4)

Chris G.
Chris G.

Reputation: 3981

Get the width/height of the image itself, not the div it is contained within.

$(window).load(function(){
    $('img.croppable').each(function(){
        var img = new Image();
        img.src =  $(this).src;
        alert(img.width);
    });
});

Upvotes: 3

zatatatata
zatatatata

Reputation: 4821

The working solution would be:

$(function(){
    $('img.croppable').each(function () {

        var original = new Image(this.src);
        original.onload = function () {
            alert(original.src + ': ' + original.width + 'x' +original.height);
        };
    });
});

Upvotes: 0

James
James

Reputation: 22246

Works in most up-to-date browsers and IE9.

$(window).load(function(){
    $('img.croppable').each(function(){
        alert(this.naturalHeight);
    });
});

Upvotes: 0

Ricardo Souza
Ricardo Souza

Reputation: 16468

You can remove the attributes, get the width and put the attributes in place again:

var $img = $(img);
var oldWidth = $img.attr("width");
var imgWidth = $img.removeAttr("width").width();

$img.width(oldWidth);

But I think Chris G.'s answer works well too, just making sure it will be loaded when you try to get the width:

img.onload = function() {
    if (!img.complete) return; // IMG not loaded
    width = img.width;
   imgManipulationGoesHere();
}

Upvotes: 0

Related Questions