需要把單通道(8位)圖像保存爲png8,該圖像數據已經通過opencv讀入,這裏需要藉助於Bitmap結構
bool save_png8(cv::Mat imgpng8, char* limgpath)
{
BITMAPFILEHEADER fileHeader;
BITMAPINFOHEADER infoHeader;
LPRGBQUAD colorTable = new RGBQUAD[256];
FILE* f = fopen(imgpath, "wb");//圖像保存路徑
if (f == NULL)
return false;
int bitCount = 8;//if bitcount is 24, there is no color table.
int colorTableSize = 0;
if (bitCount == 8)//if bitcount is 8 ,the size of color table is 256*4,4B is the size of RGBQUAD.
colorTableSize = sizeof(RGBQUAD) * 256;
int headerSize = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + colorTableSize;//the size of the header of bmp file.
int lineSize = (labelimgsubpng8.cols*bitCount / 8 + 3) / 4 * 4;//the size of each line in bmp file.
int dataSize = lineSize*labelimgsubpng8.rows;//the size of the image data of bmp file.
fileHeader.bfType = 0x4D42;//set the attribute of BITMAPFILEHEADER
fileHeader.bfSize = headerSize + dataSize;
fileHeader.bfReserved1 = 0;
fileHeader.bfReserved2 = 0;
fileHeader.bfOffBits = headerSize;
infoHeader.biSize = 40;//set the attribute of BITMAPINFOHEADER
infoHeader.biWidth = imgpng8.cols;
infoHeader.biHeight = imgpng8.rows;
infoHeader.biPlanes = 1;
infoHeader.biBitCount = bitCount;
infoHeader.biCompression = 0;
infoHeader.biSizeImage = dataSize;
infoHeader.biClrImportant = 0;
infoHeader.biXPelsPerMeter = 0;
infoHeader.biYPelsPerMeter = 0;
fwrite(&fileHeader, sizeof(BITMAPFILEHEADER), 1, f);//write the data of BITFILEHEADER to bmp file
fwrite(&infoHeader, sizeof(BITMAPINFOHEADER), 1, f);//write the data of BITINFOHEADER to bmp file
if (bitCount == 8)//if color table exists,write the data of color table to bmp file
{
for (int i = 0; i < 256; i++)
{
colorTable[i].rgbBlue = (BYTE)ColorMap[i][2];
colorTable[i].rgbGreen = (BYTE)ColorMap[i][1];
colorTable[i].rgbRed = (BYTE)ColorMap[i][0];//調色盤,可自己定義一個256行3列的數組
colorTable[i].rgbReserved = 0;
}
fwrite(colorTable, sizeof(RGBQUAD), 256, f);
}
fwrite(imgpng8.data, 1, dataSize, f);// 把opencv中的數據保存起來
fclose(f);//data writting is finished,close the bmp file.
return true;
}