如何使用FreeImage.scale保持宽高比以适配指定宽或高?
Hey there! I’ve worked with FreeImage quite a bit, so I can walk you through how to keep your image’s aspect ratio intact when using FreeImage_Scale—since there’s no built-in flag or direct method for this, you just need to do a quick manual calculation first.
Here’s the step-by-step breakdown:
Get the original image dimensions
UseFreeImage_GetWidth()andFreeImage_GetHeight()to pull the width and height of your source image.Calculate target dimensions based on aspect ratio
Decide whether you want to scale to a specific width or height, then compute the other dimension using the original image’s aspect ratio. For example:- If you want a target width of 800px:
targetHeight = (originalHeight * targetWidth) / originalWidth - If you want a target height of 600px:
targetWidth = (originalWidth * targetHeight) / originalHeight
Pro tip: Use floating-point math first to avoid integer rounding errors, then cast the result to an unsigned int at the end.
- If you want a target width of 800px:
Run the scaling function
Pass your calculated target width and height toFreeImage_Scale, along with a filter (likeFILTER_BILINEARorFILTER_BICUBIC) to get a smooth, high-quality result.
Example Code (C++)
// Assume we've already loaded our image into FIBITMAP* img unsigned int origW = FreeImage_GetWidth(img); unsigned int origH = FreeImage_GetHeight(img); // Let's scale to a target width of 1024px unsigned int targetW = 1024; unsigned int targetH = static_cast<unsigned int>( static_cast<float>(origH) * targetW / origW ); // Perform the scale with bilinear filtering for better quality FIBITMAP* scaledImg = FreeImage_Scale(img, targetW, targetH, FILTER_BILINEAR); // Don't forget to check if scaling succeeded if (!scaledImg) { // Handle error (e.g., out of memory, invalid image) return; } // Use your scaled image, then free it when done // FreeImage_Unload(scaledImg);
A couple extra notes:
- Choosing a higher-quality filter like
FILTER_BICUBICwill give you sharper scaled images, though it’s slightly slower thanFILTER_BILINEAR. - If you need to fit the image within a bounding box (e.g., max width 1024 and max height 768), compare both possible scaled dimensions and pick the one that stays within your bounds.
内容的提问来源于stack exchange,提问作者SDanks

