It is very common to scale your image to a given width and adapt the height automatically or vice versa.
There are multiple ways to approach this problem, but the most straightforward option would be to reuse and extend the code we wrote when scaling by percentage.
Given the original dimension and desired width, what would be the easiest way to calculate the change in percentage? That's correct—just divide the desired width or height by the original.
Let's assume we want to fix our width to 200 and calculate the value for scale_percentage:
new_width = 200
scale_percentage = new_width / size(source_image)[2]
Let's put it all together:
using Images, ImageView
source_image = load("sample-images/cats-3061372_640.jpg");
new_width = 200
scale_percentage = new_width / size(source_image)[2]
new_size = trunc.(Int, size(source_image) .* scale_percentage)
resized_image = imresize(source_image, new_size)
imshow(resized_image);
We have updated our scale by percentage solution to calculate scale_percentage dynamically based on a change in one of the dimensions.
Remember: size(source_image)[1] corresponds to height, while size(source_image)[2] corresponds to width.