Scaling an image to keep it under specific bounds, for visualizing purposes is a common task, but it’s even better if we can scale the image without deforming it. In this cases we have to scale the image and keep it’s original aspect ratio.
Nowadays there are thousands of libraries for any general purpose language that can perform the scaling of an image. The question is ¿which are the new width and height for the image?
Following there is this simple code, that have been tested using javascript, but should work in PHP, Python, Java, Perl, C, or whatever language you want to try
if (w < h) { h = (h * maxWidth) / w; w = maxWidth; } else { w = (w * maxHeight) / h; h = maxHeight; } |
w represents the image width
h represents the image height
maxWidth represents the maximum width boundary where the image is going to be embedded
maxHeight represents the maximum height boundary where the image is going to be embedded
As a final example, although is a copy-paste, imagine you have an image of size (w, h) and you have to fit it in an area of 640×480:
var maxWidth = 640, maxHeight = 480; if (w > maxWidth || h > maxHeight) { if (w < h) { h = (h * maxWidth) / w; w = maxWidth; } else { w = (w * maxHeight) / h; h = maxHeight; } } |