After some time, I managed to come up with the following solution:
function ResizeImage(srcwidth, srcheight, targetwidth, targetheight, letterBox, xOffset, yOffset) {
var result = { width: 0, height: 0, scaleToTargetWidth: true };
if ((srcwidth <= 0) || (srcheight <= 0) || (targetwidth <= 0) || (targetheight <= 0)) {
return result;
}
// scaling to target width
var scaleX1 = targetwidth;
var scaleY1 = (srcheight * targetwidth) / srcwidth;
// scaling to target height
var scaleX2 = (srcwidth * targetheight) / srcheight;
var scaleY2 = targetheight;
var scaleOnWidth = (scaleX2 > targetwidth);
if (scaleOnWidth) {
scaleOnWidth = letterBox;
}
else {
scaleOnWidth = !letterBox;
}
if (scaleOnWidth) {
result.width = Math.floor(scaleX1);
result.height = Math.floor(scaleY1);
result.scaleToTargetWidth = true;
}
else {
result.width = Math.floor(scaleX2);
result.height = Math.floor(scaleY2);
result.scaleToTargetWidth = false;
}
result.targetLeft = Math.floor((targetwidth - result.width) / 2 - xOffset);
result.targetTop = Math.floor((targetheight - result.height) / 2 - yOffset);
return result;
}
function ImageLoaded(event, xOffset = 0, yOffset = 0) {
var img = event.currentTarget;
var w = $(img).width();
var h = $(img).height();
var tw = $(img).parent().width();
var th = $(img).parent().height();
var result = ResizeImage(w, h, tw, th, false, xOffset, yOffset);
img.width = result.width;
img.height = result.height;
$(img).css("left", result.targetLeft);
$(img).css("top", result.targetTop);
}
.result {
width: 250px;
height: 250px;
border: thick solid #666666;
overflow: hidden;
position: relative;
border-radius: 50%;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
No offset:
<div class='result'>
<img src="http://i.imgur.com/22W12EQ.jpg" style="position: absolute;" onload="ImageLoaded(event, 0, 0);"/>
</div>
Y offset:
<div class='result'>
<img src="http://i.imgur.com/22W12EQ.jpg" style="position: absolute;" onload="ImageLoaded(event, 0, 30);"/>
</div>
The initial inspiration for this code came from a resource found here: . I made modifications to incorporate offsets for precise cropping of images.
How it operates
Create a div of any dimension and insert an image of unknown size inside it. Adjust the offsets by changing
onload="ImageLoaded(event, 0, 30);
. Positive values shift the image left or down, while negative values shift it up or right.
Note: jQuery is utilized in this script.