How would I resize a image in jQuery to a consistent aspect ratio. For example setting maximum height and have the width resize correctly. Thanks.
5 Answers
Here's a useful function that might do what you want:
jQuery.fn.fitToParent = function()
{
this.each(function()
{
var width = $(this).width();
var height = $(this).height();
var parentWidth = $(this).parent().width();
var parentHeight = $(this).parent().height();
if(width/parentWidth < height/parentHeight) {
newWidth = parentWidth;
newHeight = newWidth/width*height;
}
else {
newHeight = parentHeight;
newWidth = newHeight/height*width;
}
var margin_top = (parentHeight - newHeight) / 2;
var margin_left = (parentWidth - newWidth ) / 2;
$(this).css({'margin-top' :margin_top + 'px',
'margin-left':margin_left + 'px',
'height' :newHeight + 'px',
'width' :newWidth + 'px'});
});
};
Basically, it grabs an element, centers it within the parent, then stretches it to fit such that none of the parent's background is visible, while maintaining the aspect ratio.
Then again, this might not be what you want to do.

- 95,302
- 53
- 242
- 374
-
2Thanks, this was a massive help! – sowasred2012 Jan 08 '13 at 14:30
-
This will sometimes cause the newWidth or newHeight to be larger than the respective parent dimensions. Instead I'd recommend something like: http://stackoverflow.com/a/115492/175830 – Jason Axelson May 07 '15 at 23:20
-
1@JasonAxelson: That's entirely the point in my answer. This code ensures that both dimensions of the image are **greater than** or equal to the dimension of the parent. This aims to cover, not fill. – Eric May 08 '15 at 13:47
You could calculate this manually,
i.e.:
function GetWidth(newHeight,orginalWidth,originalHeight)
{
if(currentHeight == 0)return newHeight;
var aspectRatio = currentWidth / currentHeight;
return newHeight * aspectRatio;
}
Make sure you use the ORIGINAL values for the image otherwise it will degrade over time.
EDIT: example jQuery version (not tested)
jQuery.fn.resizeHeightMaintainRatio = function(newHeight){
var aspectRatio = $(this).data('aspectRatio');
if (aspectRatio == undefined) {
aspectRatio = $(this).width() / $(this).height();
$(this).data('aspectRatio', aspectRatio);
}
$(this).height(newHeight);
$(this).width(parseInt(newHeight * aspectRatio));
}

- 6,188
- 1
- 41
- 63
-
Is there a way to set the maximum width and height of an existing image like - ImageResize("imgID", maxWidth, maxHeight); I've tried similar techniques in PHP, but looking through the jquery plugins I couldn't find one that would do the trick. – usertest Nov 05 '09 at 18:27
-
Explain what you mean by maximum. There are max width/height css attributes, is that not what you are looking for? – Paul Nov 05 '09 at 19:16
-
Thanks. The second example is close to what I was looking for, but the example doesn't work. As far as I can tell one of the problems is that changing width or height should be set by the css() function. I tried that but the example still doesn't work. Is that because the aspectRatio isn't set? – usertest Nov 06 '09 at 15:26
-
Ignore that last comment, I got it working with the css function as follows but how could I change the function so it takes in two values newHeight and newWidth and resizes the image by aspect ratio so that neither dimension is too big? – usertest Nov 06 '09 at 16:23
-
jQuery.fn.resizeHeightMaintainRatio = function(newHeight){ if (this.aspectRatio == undefined) this.aspectRatio = parseInt($(this).css("width") / $(this).css("height")); $(this).css("height",newHeight); $(this).css("width",newHeight * this.aspectRatio); } – usertest Nov 06 '09 at 16:27
-
@Paul, instead of parseInt, it might be better to use parseFloat to get better result. Demo is here, http://jsfiddle.net/nazmul2011/sqj5m/1/ – Nazmul Mar 11 '13 at 14:45
-
Hrm...well no, you wouldn't need parseFloat, the value would already be a floating point, but I'm not sure why that parseInt is there. I think it should be on the final command instead to prevent non-integral values from being use as dimensions, which not all browsers support. – Paul Mar 11 '13 at 17:40
$("#some_image").resizable({ aspectRatio:true, maxHeight:300 });
aspectRatio: true -> maintain original aspect ratio

- 43,743
- 5
- 43
- 44
-
1Yeah, but that's a lot of overhead to invoke if you're not already using the UI. – Paul Nov 05 '09 at 18:41
-
Of course it might very well be (s)he's already trying to replicate the functionallity of the resizeable plugin...calling resizeable is going to to a whole lot more than just resize the image, btw. – Paul Nov 05 '09 at 18:45
-
IMO, If you're only using 1% of an API that could be replaced with 10 lines of code, I don't think you should you should be using the API. (Esp. with web APIs) At the same time, you need to evaluate the whole project in a case like this to make sure you aren't progressively rewriting something that already exists. – Paul Nov 05 '09 at 18:48
-
@Paul I built a resizable draggable library - there are a ton of edge cases, the library is maybe 150 lines long, and took me maybe six months to perfect. I switched to jquery ui recently - it is more powerful, works out of the box, handles the edge cases, and has hooks to add all of the functionality my library was good at. It is admittedly about ten times larger, but that is still a fraction of the size of the biggest images on the page. – Trass Vasston Aug 22 '12 at 07:27
-
@TrassVasston, reread the OP--it says nothing about allowing the USER to resize anything. I'd never suggest any lone developer try to tackle a generic problem like that on their own unless that's ALL they want to do. BTW jQuery UI is getting a bit dated, it's not being updated as much anymore and it hasn't seen much in the way of HTML5/CSS3 enhancements. The biggest problem I have with it though is that unlike jQuery, it is tightly coupled to the 'themes' which makes it awkward to drop in features, and it doesn't play well with other CSS frameworks. Perfect time for a successor. – Paul Aug 23 '12 at 13:51
There's no accounting for the amount of copy and pasters out there eh! I also wanted to know this and all I saw were endless examples of scaling width OR height.. who would want the other overflowing?!
- Resize width AND height without the need for a loop
- Doesn't exceed the images original dimensions
- Uses maths that works properly i.e width/aspect for height, and height*aspect for width so images are actually scaled properly up and down :/
Should be straight forward enough to convert to javascript or other languages
//////////////
private void ResizeImage(Image img, double maxWidth, double maxHeight)
{
double srcWidth = img.Width;
double srcHeight = img.Height;
double resizeWidth = srcWidth;
double resizeHeight = srcHeight;
double aspect = resizeWidth / resizeHeight;
if (resizeWidth > maxWidth)
{
resizeWidth = maxWidth;
resizeHeight = resizeWidth / aspect;
}
if (resizeHeight > maxHeight)
{
aspect = resizeWidth / resizeHeight;
resizeHeight = maxHeight;
resizeWidth = resizeHeight * aspect;
}
img.Width = resizeWidth;
img.Height = resizeHeight;
}

- 62,658
- 20
- 139
- 163
-
If height and width of image are both smaller than maxHeight, maxWidth it won't scale the image up. – tech20nn Jun 12 '12 at 13:56
This is a good solution if you need perfect height and width aspect ratio after crop it will give perfect crop ratio
getPerfectRatio(img,widthRatio,heightRatio){
if(widthRatio < heightRatio){
var height = img.scalingHeight - (img.scalingHeight % heightRatio);
var finalHeight = height
var finalWidth = widthRatio * (height/heightRatio);
img.cropHeight = finalHeight;
img.cropWidth = finalWidth
}
if(heightRatio < widthRatio){;
var width = img.scalingWidth - (img.scalingWidth % widthRatio);
var finalWidth = width;
var finalHeight = heightRatio * (width/widthRatio);
img.cropHeight = finalHeight;
img.cropWidth = finalWidth
}
return img
}

- 21
- 2