You want to scale the images uniformly, by a scaling factor computed separately for each image. If you take the longer dimension and divide it into 32 (32.0 / max(width, height)
), then you'll get a number that you can multiply the width and height by.
scale = 32.0 / max(width, height)
scaledWidth = round(width * scale, 0)
scaledHeight = round(height * scale, 0)
This gets you halfway there, because the larger dimension is now 32 -- the smaller one might be something less than 32. So, you need to pad the image in the smaller dimension to make up the difference. How much do you pad it? Well, the total padding is going to be 32 - min(scaledWidth, scaledHeight)
. You want to put half on one side and half on the other. One potential problem is that it might be an odd number of pixels -- a simple way to handle that is to put half on one side and the rest on the other.
totalPadding = 32 - min(scaledWidth, scaledHeight)
paddingBefore = math.floor(totalPadding / 2) # <-- "half" before
paddingAfter = totalPadding - paddingBefore # <-- "the rest" after
Then you just need to resize the image. I must confess that I am actually unfamiliar with the image processing functions you have at your disposal. However, the gist of it is:
- Create a new image that is 32x32.
- (Optional) If you want to ensure that the extended background is the same as the original image's background, since you mentioned it will be either black or white, then fill the 32x32 image with the same colour you find at coordinate (0, 0) of the original image.
- Draw the original image into the new image, specifying that you want to resize it. You'll need to determine whether the image is portrait or landscape -- if it is portrait, then you want to draw it at position
(paddingBefore, 0)
, otherwise you want to draw it at position (0, paddingBefore)
. Most graphics frameworks I have worked with allow you to specify a "source" and a "destination" rectangle, so your source rectangle will be (0, 0)-(width, height)
, and your dest rectangle will be of size (scaledWidth, scaledHeight)
, and at the origin described above, depending on whether the image is wider or taller.