使用GDI+保存图像为8bpp的灰度图像

使用GDI+保存图像为8bpp的灰度图像,GDI+真的有些特殊。。。。。哭


//   Greyscale conversion
#define GREY(r, g, b) (BYTE)(((WORD)r * 77 + (WORD)g * 150 + (WORD)b * 29) >> 8)	// .299R + .587G + .114B
//#define GREY(r, g, b) (BYTE)(((WORD)r * 169 + (WORD)g * 256 + (WORD)b * 87) >> 9)	// .33R + 0.5G + .17B


// BOOL GDIPlusImage::SaveToFileWith8pp(TCHAR *pszPath)
// 功能:保存图片为8位的灰度图像
// 参数: pszPath要保存的文件名
BOOL GDIPlusImage::SaveToFileWith8pp(TCHAR *pszPath)
{
	Bitmap *ima = this->m_pBitmap;		// GDIPlusImage的Bitmap对象

	if (!ima || !pszPath || !*pszPath)
	{
		return FALSE;
	}

	int width = m_pBitmap->GetWidth();
	int height = m_pBitmap->GetHeight();
	int bitcount = 8;			//1, 4, 8, 24, 32

	//
	//Build bitmap header
	BITMAPFILEHEADER bitmapFileHeader; 
	BITMAPINFOHEADER bitmapInfoHeader; 
	BYTE			 rgbquad[4];			// RGBQUAD
	int				 index = 0;

	DWORD stride = ((bitcount*width + 31)/32)*4;		//每行都是4的倍数,或者说是DWORD大小的倍数

	switch(bitcount) { 
	case 1: 
		index = 2; 
		bitmapFileHeader.bfOffBits = (DWORD)(sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + 2*4); 
		break; 
	case 4: 
		index = 16; 
		bitmapFileHeader.bfOffBits = (DWORD)(sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + 16*4); 
		break; 
	case 8: 
		index = 256; 
		bitmapFileHeader.bfOffBits = (DWORD)(sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + 256*sizeof(RGBQUAD)); 
		break; 
	case 24: 
	case 32: 
		index = 0; 
		bitmapFileHeader.bfOffBits = (DWORD)(sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER)); 
		break; 
	default:
		break;
	} 

	//构造Bitmap文件头BITMAPFILEHEADER 
	bitmapFileHeader.bfType = 0x4d42;    // 很重要的标志位  BM 标识
	bitmapFileHeader.bfSize = (DWORD)(bitmapFileHeader.bfOffBits + height * stride);		//bmp文件长度  
	bitmapFileHeader.bfReserved1 = 0; 
	bitmapFileHeader.bfReserved2 = 0; 

	//构造Bitmap文件信息头BITMAPINFOHEADER 
	bitmapInfoHeader.biSize = sizeof(BITMAPINFOHEADER); 
	bitmapInfoHeader.biWidth = width; 
	bitmapInfoHeader.biHeight = height; 
	bitmapInfoHeader.biPlanes = 1; 
	bitmapInfoHeader.biBitCount = bitcount;
	bitmapInfoHeader.biCompression = BI_RGB;				// 未压缩
	bitmapInfoHeader.biSizeImage = height * stride; 
	bitmapInfoHeader.biXPelsPerMeter = 3780; 
	bitmapInfoHeader.biYPelsPerMeter = 3780; 
	bitmapInfoHeader.biClrUsed = 0; 
	bitmapInfoHeader.biClrImportant = 0; 

	//创建BMP内存映像,写入位图头部
	BYTE *pMyBmp = new BYTE[bitmapFileHeader.bfSize];		// 我的位图pMyBmp
	BYTE *curr = pMyBmp;									// curr指针指示pMyBmp的位置
	memset(curr, 0, bitmapFileHeader.bfSize); 

	//写入头信息 
	memcpy(curr, &bitmapFileHeader,sizeof(BITMAPFILEHEADER));
	curr = pMyBmp + sizeof(BITMAPFILEHEADER); 
	memcpy(curr, &bitmapInfoHeader,sizeof(BITMAPINFOHEADER)); 
	curr += sizeof(BITMAPINFOHEADER);

	//构造调色板 
	if(8 == bitcount) 
	{
		rgbquad[3] = 0;										//rgbReserved
		for(int i = 0; i < 256; i++) 
		{ 
			rgbquad[0] = rgbquad[1] = rgbquad[2] = i; 
			memcpy(curr, rgbquad, sizeof(RGBQUAD)); 
			curr += sizeof(RGBQUAD); 
		} 
	}else if (4 == bitcount)
	{
		rgbquad[3] = 0;
		for (int i = 0; i < 16; i++)
		{
			rgbquad[0] = rgbquad[1] = rgbquad[2] = i; 
			memcpy(curr, rgbquad, sizeof(RGBQUAD)); 
			curr += sizeof(RGBQUAD); 
		}
	}
	else if(1 == bitcount) 
	{ 
		rgbquad[3] = 0;										//rgbReserved
		for(int i = 0; i < 2; i++) 
		{ 
			rgbquad[0] = rgbquad[1] = rgbquad[2] = (256 - i)%256; 
			memcpy(curr, rgbquad, sizeof(RGBQUAD)); 
			curr += sizeof(RGBQUAD); 
		} 
	}

	//用GDI+加载数据源,也可以是其他的,写入文件数据
	Rect rect(0,0,width,height);		// Gdiplus+
	BitmapData bmData;
	Status iSucess = ima->LockBits(
		&rect,
		ImageLockModeRead,
		ima->GetPixelFormat() ,
		&bmData);

	BYTE *_pixels = (BYTE*)bmData.Scan0;	//原图rect区域内存位置的起始指针,以BYTE作为单元类型
	BYTE *_pRow;
	int _strideoff8 = stride - width;			//前面计算的索引图像的stride
	BYTE _grey;

	// build pixles, GDI+ (windows)的图像数据的原点在左下角,参考一下OpenCV的IplImage结构体
	switch(ima->GetPixelFormat())
	{
	case PixelFormat24bppRGB:
		{
			int _strideoff24 = stride - 3*width;			//前面计算的索引图像的stride

			//  灰度化
			for (int i=height-1; i >= 0; i--)
			{
				_pRow = _pixels + i*bmData.Stride;		// 当前的行

				for (int j=width-1; j >= 0; j--)
				{	
					BYTE* _pixels_b;		//b
					BYTE* _pixels_g;		//g
					BYTE* _pixels_r;		//r
					
					_pixels_b = _pRow++;  //blue
					_pixels_g = _pRow++;  //green
					_pixels_r = _pRow++;  //red

					_grey = GREY(*_pixels_r, *_pixels_g, *_pixels_b); 

					*curr = _grey;    //根据红绿蓝求出此像素的灰度值
					curr++;
				}
				curr += _strideoff8;
			}
		}
		break;

	case PixelFormat32bppARGB:
		{
			//  灰度化
			for (int i=height-1;i>=0;i--)
			{
				_pRow = _pixels + i*bmData.Stride;
				
				for (int j=width-1;j>=0;j--)
				{			
					BYTE* _pixels_b;
					BYTE* _pixels_g;		
					BYTE* _pixels_r;		

					_pixels_b = _pRow++;  //blue
					_pixels_g = _pRow++;  //green
					_pixels_r = _pRow++;  //red
					_pRow++;

					_grey = GREY(*_pixels_r, *_pixels_g, *_pixels_b); 

					*curr = _grey;
					curr++;
				}
				curr += _strideoff8;
			}
		}
		break;
	case PixelFormat8bppIndexed:  // Gdi+只能保存成24位真彩色的图像
		{
			// 不能直接用memcpy复制,需要水平镜像,memcpy(curr, _pixels, height * stride);
			for (int i=height-1; i >= 0; i--)
			{
				_pRow = _pixels + i*bmData.Stride;
// 				for (int j=width-1;j >= 0;j--)
// 				{	
// 					_grey = *_pRow++; 
// 					*curr = _grey; 
// 					curr++;
// 				}
				memcpy(curr, _pRow, width);
				curr += stride;
			}
		}
		break;
	default:
		break;
	}

	// 保存图像 pMyBmp 到文件
	try
	{
		CFile f(pszPath, CFile::modeCreate | CFile::modeWrite );
		f.Write(pMyBmp, bitmapFileHeader.bfSize);
		f.Close();
	}
	catch( CFileException* e )
	{
		TCHAR szCause[255];
		e->GetErrorMessage(szCause, 255);

		CString msg;
		msg.Format(_T("file error: %s, m_cause:%d\n"),szCause, e->m_cause);

		TRACE1("%s",msg);
		AfxMessageBox(msg);
		e->Delete();
	}

	//clean:
	ima->UnlockBits(&bmData);
	delete[] pMyBmp;

	return TRUE;
}


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,您可以参考以下代码: ```c #include <stdio.h> int main() { FILE *fp; unsigned char header[54]; unsigned char R,G,B; int height, width; int padding = 0; int bpp = 0; // bits per pixel fp = fopen("input.bmp", "rb"); if(fp == NULL){ printf("Error: unable to open image.\n"); return -1; } // Read bitmap header for(int i=0; i<54; i++){ header[i] = getc(fp); } // Read image dimensions width = *(int *)&header[18]; height = *(int *)&header[22]; bpp = *(int *)&header[28]; // Calculate padding (if any) for image scanlines if((width*bpp)%4 != 0){ padding = 4 - ((width*bpp)/8)%4; } // Print image dimensions to console printf("Image dimensions:\n"); printf("- Width: %d pixels\n", width); printf("- Height:%d pixels\n", height); printf("- Bits per pixel: %d\n", bpp); printf("- Padding: %d\n", padding); // Read pixel data, convert to grayscale, and write to new file unsigned char pixel[3]; FILE *out = fopen("output.bmp", "wb"); int i, j; unsigned char avg; fwrite(header, sizeof(unsigned char), 54, out); for(i=0; i<height; i++){ for(j=0; j<width; j++){ // Read pixel data fread(pixel, sizeof(unsigned char), 3, fp); // Convert to grayscale avg = (unsigned char)((pixel[0]*0.3) + (pixel[1]*0.59) + (pixel[2]*0.11)); // Write grayscale pixel to output file fwrite(&avg, sizeof(unsigned char), 1, out); fwrite(&avg, sizeof(unsigned char), 1, out); fwrite(&avg, sizeof(unsigned char), 1, out); } // Write padding, if any for(int k=0; k<padding; k++){ fwrite(&B, sizeof(unsigned char), 1, out); } } fclose(fp); fclose(out); printf("Image converted successfully!\n"); return 0; } ``` 此程序可以将输入的位图文件转换为灰度图像,并输出到新文件中。该程序使用了 C 语言来实现,首先读入位图文件的头信息,然后计算出像素数据在文件中的偏移量,接着读取像素数据并将其转换为灰度值,最后将灰度值写回到输出文件中。 希望能解决您的问题,如有疑问欢迎继续询问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值