Constrain aspect ratio forimage using javascript

This post explains how to calculate the constrain aspect ration for a image. In this example we are calculating the constrain image size based on the original size the image.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
$(document).ready(function(){
 //calc height if constrain aspect ratio
$('#widthimgrichMedia').keyup(function() {
                if ($('#imgConstrain').is(':checked')) {
                    var old_width = $('#imageSize').width();
                    var old_height = $('#imageSize').height();
                    var new_width = $('#widthimgrichMedia').val();
                    var new_height = Math.round(new_width / (old_width / old_height));
                    $('#heightimgrichMedia').val(new_height);
                }
            });

 //calc width if constrain aspect ratio
            $('#heightimgrichMedia').keyup(function() {
                if ($('#imgConstrain').is(':checked')) {
                    var old_width = $('#imageSize').width();
                    var old_height = $('#imageSize').height();
                    var new_height = $('#heightimgrichMedia').val();
                    var new_width = Math.round((old_width / old_height) * new_height);
                    $('#widthimgrichMedia').val(new_width);
                }
            })
  });
<input type="checkbox" id="imgConstrain" /> Constrain
Width: <input type="text" value="" id="widthimgrichMedia" style="width:50px;" />
Height: <input type="text" value="" id="heightimgrichMedia" style="width:50px;"  />

We have two keyup function to calculate the constrain images height and width. If the constrain check box is checked both the function will work in key up. These are the two calculation we have used to calculate the new constrain height and width.

1
2
var new_height = Math.round(new_width / (old_width / old_height)); // calculate height
var new_width = Math.round((old_width / old_height) * new_height); // calculate width