The code below works very well for resizing an image by aspect ratio by height and I can also create a separate function by width. But i m not always sure if an image will need to be shrunk by height or width.
For example if the space that the image needs to be resized into is 100 width and 100 height and an image is 150 by 90 then its the width that would need to be shrunk. If the image is 80 by 160 then the height would need to be shrunk.
So what i m asking is how could the code below be modified so it shrinks an image by aspect ratio to fit parameters of both width and height? Thanks.
jQuery.fn.resizeHeightMaintainRatio = function(newHeight){
if (this.aspectRatio == undefined)
this.aspectRatio = parseInt($(this).width() / $(this).height());
$(this).height(newHeight);
$(this).width(newHeight * this.aspectRatio);
}
I ve edited the code yet again, since on further inspection neither my updated version nor Dan s seemed to work properly. The aspect ratio was lost so here s yet another. I ve tried it on one image and so far so good. Here it is,
jQuery.fn.resizeMaintainRatio = function(newHeight, newWidth){
widthRatio = parseInt($(this).width() / newWidth);
heightRatio = parseInt($(this).height() / newHeight);
if(heightRatio > widthRatio)
{
this.aspectRatio = parseInt($(this).css("width") / $(this).css("height"));
$(this).css("height", newHeight);
$(this).css("width", newHeight * this.aspectRatio);
}
else{
this.aspectRatio = parseInt($(this).css("height") / $(this).css("width"));
$(this).css("width", newWidth);
$(this).css("height", newWidth * this.aspectRatio);
}
}
NOTE AGAIN: after further use the above code works very strangely, try this instead - http://plugins.jquery.com/project/kepresize