如何使用FreeImage获取子图像

时间:2017-04-01 13:25:03

标签: c++ opengl freeimage loadimage

如标题所述,我在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像素区域)?

1 个答案:

答案 0 :(得分:1)

您可以使用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");