How to maximize view of image with prevent aspect ratio using javascript function.

The simple question is when you want to view an image resize and show its maximum view you have to use the javascrpt function

First of all you have to get the object of image using javascript and jquery so that you can easily get it.

we have use each() event function in jquery to get the object of image.

i have define two functions to proceed this to work.

one is – maintainImageAspectRatio()

second is – ScaleImage()

the first code of function is below,

function maintainImageAspectRatio() {
$(‘img’).each(function() {
var img = this;
// what’s the size of this image and it’s parent
var w = $(img).width();
var h = $(img).height();
var tw = $(img).parent().width();
var th = $(img).parent().height();

// compute the new size and offsets
var result = ScaleImage(w, h, tw, th, true);    ///The second function to resize image with aspect ratio

// adjust the image coordinates and size
img.width = result.width;
img.height = result.height;
$(img).css(“left”, “0”);
$(img).css(“top”, “-40px”);
$(img).css(“right”, “0”);
$(img).css(“bottom”, “0”);
$(img).css(“position”, “absolute”);
$(img).css(“margin”, “auto”);
});
}

 

The second function to resize the image

function ScaleImage(srcwidth, srcheight, targetwidth, targetheight, fLetterBox) {

var result = { width: 0, height: 0, fScaleToTargetWidth: true };

if ((srcwidth <= 0) || (srcheight <= 0) || (targetwidth <= 0) || (targetheight <= 0)) {
return result;
}

// scale to the target width
var scaleX1 = targetwidth;
var scaleY1 = (srcheight * targetwidth) / srcwidth;

// scale to the target height
var scaleX2 = (srcwidth * targetheight) / srcheight;
var scaleY2 = targetheight;

// now figure out which one we should use
var fScaleOnWidth = (scaleX2 > targetwidth);
if (fScaleOnWidth) {
fScaleOnWidth = fLetterBox;
}
else {
fScaleOnWidth = !fLetterBox;
}

if (fScaleOnWidth) {
result.width = Math.floor(scaleX1);
result.height = Math.floor(scaleY1);
result.fScaleToTargetWidth = true;
}
else {
result.width = Math.floor(scaleX2);
result.height = Math.floor(scaleY2);
result.fScaleToTargetWidth = false;
}
result.targetleft = Math.floor((targetwidth – result.width) / 2);
result.targettop = Math.floor((targetheight – result.height) / 2);

return result;    //return the resized object of image
}

 

the above two function is used properly in javascript in <script> tag.