// load png image with freeimage. #include #include #include const char *outfile = "out.png"; int main(int argc, char *argv[]) { if (argc != 2) { printf("Usage:\n\t01_load_png01.exe IN.png\n"); return -1; } FreeImage_Initialise(FALSE); printf("FreeImage ver. %s\n", FreeImage_GetVersion()); printf("%s\n\n", FreeImage_GetCopyrightMessage()); try { auto filename = argv[1]; // get input image format FREE_IMAGE_FORMAT fif = FIF_UNKNOWN; int flag = 0; fif = FreeImage_GetFileType(filename); if (fif == FIF_UNKNOWN) fif = FreeImage_GetFIFFromFilename(filename); if (fif == FIF_PNG) flag = PNG_DEFAULT; else if (fif == FIF_BMP) flag = BMP_DEFAULT; else if (fif == FIF_GIF) flag = GIF_DEFAULT; else if (fif == FIF_JPEG) flag = JPEG_DEFAULT; // load image FIBITMAP *image = FreeImage_Load(fif, filename, flag); if (image) printf("Load : %s\n", filename); else throw std::runtime_error("Load failed"); // convert to 24bit image FIBITMAP *image24 = FreeImage_ConvertTo24Bits(image); // convert greyscale int width = FreeImage_GetWidth(image24); int height = FreeImage_GetHeight(image24); FIBITMAP *newimg = FreeImage_Allocate(width, height, 24); RGBQUAD col; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { FreeImage_GetPixelColor(image24, x, y, &col); double ncol = 0.299 * col.rgbRed + 0.587 * col.rgbGreen + 0.114 * col.rgbBlue; if (ncol < 0) ncol = 0; if (ncol > 255) ncol = 255; col.rgbRed = int(ncol); col.rgbGreen = int(ncol); col.rgbBlue = int(ncol); FreeImage_SetPixelColor(newimg, x, y, &col); } } // save png image if (FreeImage_Save(FIF_PNG, newimg, outfile, PNG_DEFAULT)) printf("Save : %s\n", outfile); else throw std::runtime_error("Save failed"); FreeImage_Unload(image); FreeImage_Unload(newimg); } catch (std::exception &e) { std::cout << "exception!\n" << e.what() << std::endl; } FreeImage_DeInitialise(); return 0; }