holyredbeard
holyredbeard

Reputation: 21178

Scaling image and keeping its proportions

I'm working on a photo sharing site. When displaying an image in full size I want the width to be of maximum 800px, as well as the height to be of maximum 600.

The code below works for scaling, but it doesn't keep the image's proportions. I guess I could use percentage instead, but I still want the image to have these specific maximum values (h: 800, w: 600).

Is there a way of accomplishing that with jQuery?

Thanks in advance!

    if ($('#photo').length > 0) {
        var imgWidth = $("#photo").width();
        var imgHeight = $("#photo").height();

        if (imgWidth > 800) {
            $("#photo").width(800);
        }
        if (imgHeight > 600) {
            $("#photo").height(600);
        }
    }

Upvotes: 1

Views: 147

Answers (3)

Etienne Dupuis
Etienne Dupuis

Reputation: 13786

you could use max-width or max-height

Upvotes: 4

ZeroOne
ZeroOne

Reputation: 3161

Something like this:

var imgWidth = $("#photo").width();
var imgHeight = $("#photo").height();
var maxWidth = 800;
if (imgWidth > maxWidth) {
    var newWidthMultiplier = maxWidth / imgWidth;
    $("#photo").width(maxWidth);
    $("#photo").height(newWidthMultiplier * imgHeight);
}

Upvotes: 1

Mark Ransom
Mark Ransom

Reputation: 308111

The key is to multiply both the width and the height by the same scaling constant.

If you're limiting by the width, multiply by 800/width.

If you're limiting by the height, multiply by 600/height.

Upvotes: 1

Related Questions