如何使用 FreeImage 获取子图像

How to get subimage with FreeImage

如标题所述,我在我的 OpenGL 游戏中使用 FreeImage 加载纹理,但如何获取子图像?

我当前的代码如下所示:

    FREE_IMAGE_FORMAT fif = FIF_UNKNOWN;
    FIBITMAP* dib = nullptr;
    fif = FreeImage_GetFileType(filename, 0);
    if (fif == FIF_UNKNOWN)
        fif = FreeImage_GetFIFFromFilename(filename);
    if (fif == FIF_UNKNOWN)
        return nullptr;

    if (FreeImage_FIFSupportsReading(fif))
        dib = FreeImage_Load(fif, filename);
    if (!dib)
        return nullptr;

    BYTE* pixels = FreeImage_GetBits(dib);
    *width = FreeImage_GetWidth(dib);
    *height = FreeImage_GetHeight(dib);
    *bits = FreeImage_GetBPP(dib);

    int size = *width * *height * (*bits / 8);
    BYTE* result = new BYTE[size];
    memcpy(result, pixels, size);
    FreeImage_Unload(dib);
    return result;

我需要更改什么才能获得子图像(例如左上角的 32x32 像素区域)?

您可以使用FreeImage_Copy()获取指定区域的子图像。请注意 FreeImage_Copy() 采用 left, top, right, bottom 而不是 x, y, width, height.

FIBITMAP *image = ...;

int x = 0;
int y = 0;
int width = 32;
int height = 32;

FIBITMAP *subimage = FreeImage_Copy(image, x, y, x + width, y + height);

记住 FreeImage_Unload(subimage) 因为它是给定图像的文字副本。

如果需要,您可以通过以下操作将其保存为 PNG:

if (FreeImage_Save(FIF_PNG, subimage, "subimage.png"))
    printf("Subimage successfully saved!\n");
else
    printf("Failed saving subimage!\n");