A couple of times I have had to deal with images in my code. Recently I had a project that needed the user to upload an image, which then needed to be scaled down to fit an area. Below I detail the calculations that I used.

For this demonstration we will be using an image with the pixel size of 300 x 320. We want to scale it down to an image size of 155 x 200. This size would allow us to scale an image for a regular passport image of 35mm x 45mm.

The first thing you need to do is work out which side will be scaled down the most. Using the following to work out the percentage of the scale.

// Width Percentage = New Width / Current Width
intWidth = 155 / 300

// Height Percentage = New Height / Current Height
intHeight = 200 / 320

// intWidth = 0.51666,  intHeight = 0.625

Now we can see that the Height is bigger than the width percentage wise.

We dont want any white spaces, we are happy to crop off unwanted parts of the image, so we will scale down using the height, using the below formula:

(orignal height / original width) x new height = new width
(320 / 300) x 200 = 213.33

If we wanted the whole image to fit into our assigned area, we would scale down using the width instead, because the percentage was smaller.

(orignal height / original width) x new width = new height
(320 / 300) x 155 = 165.33

Hopefully this will allow you to incorporate this into your calculations if your current programming language doesn’t allow for it.

I used this in Imagik in PHP which has a Scale Image function which was useful.

Other useful tools on the internet when understanding scale and percentages can be found on this Math.com page. Andrew Hedges also has a good Online Aspect Ratio Calculator if you just need it for a one-off.

Join the conversation...

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.