当前位置:C++技术网 > 资讯 > GDI+实现往像框中添加图片

GDI+实现往像框中添加图片

更新时间:2015-10-08 21:21:12浏览次数:1+次

    原有的GDI编程中,并没有透明度这一概念,因此如果想通过编程的方式来实现图片的合成,就相当麻烦在GDI+,只需要设定每一个像素的透明度,便能够实现图拍你的简单合成。接着我们往像框中添加照片,说明透明度在图片合成中的具体运用。

上图中第一个的图片,除了相框的边界以外,其余的色彩均为白色。再像框中添加照片的过程实际上是在照片上重新覆盖一副像框图片,只不过要保证相框的白色部分消失。其实很简单,我们只要让像框中的白色部分保持100%的透明就行了。
GDI+中对像素的访问是通过的Bitmap对象的GetPixel(获得像素)函数来实现,该函数的调用方法:

status GetPixel
(int x,
int y,
Color* color);
x,y:像素的位置。
color:像素信息返回值。
void CInsertPhotoDlg::OnInsertphoto() 
{
	// TODO: Add your control notification handler code here
	this->RedrawWindow();
	CDC* pDC = GetDC();
	Graphics graphics(pDC->m_hDC);
	int Alpha;

	//////装入用于显示的相框和图片////////
	Bitmap photoframe(L"photoframe.bmp");
	Bitmap photo(L"niao.bmp");
	//////得到相框的尺寸//////
	int iWidth = photoframe.GetWidth();
	int iHeight = photoframe.GetHeight();
	/////////复制相框////////////
	Bitmap* Ori_photoframe = photoframe.Clone(0, 0, iWidth, iHeight, PixelFormatDontCare);
	Color color, colorTemp;
	for (int iRow = 0;iRow < iHeight;iRow++)
	{
		for (int iColumn = 0;iColumn < iWidth;iColumn++)
		{
			photoframe.GetPixel(iColumn, iRow, &color);
			/////////////如果该像素的颜色的为白色,设定其透明度为完全透明
			if ((color.GetRed() == 255) && (color.GetGreen() ==255) && (color.GetBlue() == 255))
			{
				Alpha = 0;
			}
			else
			{
				Alpha = 255;
			}
			colorTemp.SetValue(color.MakeARGB(Alpha, color.GetRed(), color.GetGreen(), color.GetBlue()));
			//////////////重新设定像素的色彩值//////////////
			photoframe.SetPixel(iColumn, iRow, colorTemp);
		}
	}
	graphics.DrawImage(Ori_photoframe,0, 0, iWidth / 2, iHeight / 2);
	/////////////进行照片与像框的合成/////////////
	graphics.DrawImage(&photo, 50,30, iWidth / 3, iHeight / 3);

}
DrawImage函数就是在指定的位置x,y,画上参数x,y随后参数表示的的矩形块。
这个程序主要就是通过对位图的像素进行逐一访问来修改其透明度,这种方法使用起来比较灵活,最大的特点是可以有选择的设置透明度。