The easiest way to convert between image formats is to use the CImage class, shared by MFC and ATL, and defined in the atlimage.h header file.
CImage image; HRESULT res = image.Load("in.bmp"); image.Save("out.jpg"); image.Save("out.gif"); image.Save("out.png"); image.Save("out.tif");
If you have an RGB buffer and want to create a bitmap: just create and save the bitmap header in a file and add an RGB buffer to it.
To create a header, you can use BITMAPFILEHEADER , BITMAPINFOHEADER and RGBQUAD from the GDI defined in the WinGDI.h header
Here is an example of how to populate the header data:
BITMAPINFOHEADER bmpInfoHdr; bmpInfoHdr.biSize = sizeof(BITMAPINFOHEADER); bmpInfoHdr.biHeight = nHeight; bmpInfoHdr.biWidth = nWidthPadded; bmpInfoHdr.biPlanes = 1; bmpInfoHdr.biBitCount = bitsPerPixel; bmpInfoHdr.biSizeImage = nHeight * nWidthPadded * nSPP; bmpInfoHdr.biCompression = BI_RGB; bmpInfoHdr.biClrImportant = 0; bmpInfoHdr.biClrUsed = 0; bmpInfoHdr.biXPelsPerMeter = 0; bmpInfoHdr.biYPelsPerMeter = 0; bmpFileHdr.bfType = BITMAP_FORMAT_BMP; bmpFileHdr.bfSize = (DWORD) (sizeof(BITMAPFILEHEADER) + bmpInfoHdr.biSize + sizeof(RGBQUAD)*numColors + bmpInfoHdr.biSizeImage); bmpFileHdr.bfReserved1 = 0; bmpFileHdr.bfReserved2 = 0; bmpFileHdr.bfOffBits = (DWORD) (sizeof(BITMAPFILEHEADER) + bmpInfoHdr.biSize + sizeof(RGBQUAD)*numColors);
Keep in mind that bitmaps are stored in reverse order and that the image width should be aligned to DWORD, except for Rm-compressed bitmaps (they must be a multiple of 4 bytes, add indentation if necessary).
if ((nWidth%4) != 0) nPadding = ((nWidth/4) + 1) * 4;
When saving the buffer, add the required padding to each line ...
To summarize, these are the necessary steps to create a bitmap file from the rgb buffer:
//1. create bmp header //2. save header to file: write(file, &bmpFileHdr, sizeof(BITMAPFILEHEADER)); write(file, &bmpInfoHdr, sizeof(BITMAPINFOHEADER)); write(file, &colorTable, numColors * sizeof(RGBQUAD)); //3. add rgb buffer to file: for(int h=0; h<nHeight; h++) { for(int w=0; w<nWidth; w++) { //3.a) add row to file //3.b) add padding for this row to file } }