You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用FreeImage.scale保持宽高比以适配指定宽或高?

Maintaining Aspect Ratio with 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:

  1. Get the original image dimensions
    Use FreeImage_GetWidth() and FreeImage_GetHeight() to pull the width and height of your source image.

  2. 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.
  3. Run the scaling function
    Pass your calculated target width and height to FreeImage_Scale, along with a filter (like FILTER_BILINEAR or FILTER_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_BICUBIC will give you sharper scaled images, though it’s slightly slower than FILTER_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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:40:08