As stated in the title, I am using FreeImage to load textures in my OpenGL game, but how do I get subimages?
My current code looks like this:
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;
What would I need to change to get the subimage (for example a 32x32 area of pixels in the top left corner)?
You can use FreeImage_Copy()
to get a subimage of a specified region. Note that FreeImage_Copy()
takes left, top, right, bottom
and not 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);
Remember to FreeImage_Unload(subimage)
as it is a literal copy of the given image.
If needed you could then save it to a PNG by doing:
if (FreeImage_Save(FIF_PNG, subimage, "subimage.png"))
printf("Subimage successfully saved!\n");
else
printf("Failed saving subimage!\n");