Reputation: 125325
I have 2 images, Image 1 and Image 2.
Image 1 has a size of 512(width) x 515(height).
Then Image 2 with size of 256(width) x 256(height).
Image 2 is will be used as a watermark and will be placed on top of Image 1.
I want Image 2 size to be dependent on Image 1 size. Image 2 can resize up or down depending on the size of Image 1.
The new size(width & height) of Image 2 should be 20 percent size of Image 1 and the-same time preserve its aspect ratio.
What's the algorithm to find the new size(width & height) of Image 2?
Right now, I use (20%/100) * 512
to resize it, but this does not preserve Image 2 aspect ratio.
Upvotes: 1
Views: 983
Reputation: 24417
If the two images don't have the same aspect ratio then it's mathematically impossible to scale both width and height by 20% and preserve the aspect ratio.
So, chose an axis that you will use to scale by, and scale the other one to the size that preserves the aspect ratio.
e.g, using width:
new_image1_width = 512 * (20 / 100) = 102.4
Then compute the new height to preserve the aspect ratio:
original_aspect_ratio = image2_width / image2_height = 256 / 256 = 1
new_image1_height = 102.4 / original_aspect_ratio = 102.4
Or do it the other way (this time multiplying by the ratio):
new_image1_height = 515 * (20 / 100) = 103
original_aspect_ratio = image2_width / image2_height = 256 / 256 = 1
new_image1_width = 103 * original_aspect_ratio = 103
If you have to handle arbitrary image sizes and arbitrary scale factors, you will need two switch between the two ways depending on what you want the rule to be. E.g. you could always go with the smaller of the two, or use a ratio-adjusted height unless this gives you a height larger than image 1 height, and in that case use the second way, or vice versa.
Upvotes: 2