An image gallery sometimes needs images to be a specific height and width to allow a beautiful presentation without distortion from the wrong aspect ratio. This article highlights a function we've developed to handle these calculations. We use image uploading in different way throughout our applications, but the need to calculate resizing is consistent. This function can be optimized further and is verbose, but that is intentional to provide clarity on the process.
The objective of this function is to accept arguments that include the image's original height and width as well as the desired height and width. Any physical resizing or cropping of the image is performed outside this function, as this is exclusively used to return the new height, new width and instructions for cropping the image.
This is used in a gallery with a specific height and width specified in application variables. All images uploaded must end up to be within these settings, whether the image are smaller or larger than the desired image size. When an image upload occurs, it is handed off to a function to resize the image. The resize function calls this function.
One important note is how we handle a portrait image versus a landscape image. A portrait image will not fill the width of the space in the gallery without expanding the height of the gallery. We wanted the gallery to stay the same size for all images. A portrait image is resized to the right height, however, it will always fit the desired width. A landscape image can be a little tricky. If the landscape image is an odd shape or there isn't a standard aspect ratio, then we need to crop part of the image.
The first part of the process is to calculate what the new height would be if we resized the image to the desired width. Then, we calculate what the new width would be if we resized the image to the desired height. If one of those calculations is less than the desired height or width, then we will resize the image in that direction, which will end up having overlap in the other direction.
Let's say our application variables are set to a height and width of 1024W x 768H and our image is 1500W x 1100H. If we resize the image based on the width, the image size will be calculated as follows.
((Desired Width/Original Width) x Original Height) = New Height
((1024/1500) x 1100) = 751px
The new height is not within the range we have for our application variables. We need to resize the height first and then examine the width.
((Desired Height/Original Height) x Original Width) = New Width
((768/1100) x 1500) = 1047px
The new width calculation exceeds the desired width, but the height is what we want. The next step is to calculate how much will be cropped, which is the absolute value of the desired width subtracting the new width calculation. In this case, it's ABS(1047-1024) = 23px. The function returns the instructions to crop the image width by 23px after the image is resized to the desired height.