GDI+初探之图像透明显示和保存

来源:互联网 发布:python xml dom 编辑:程序博客网 时间:2024/04/29 16:01

GDI+ 的配置                                                                                                      

1.  引入库文件

以MFC 单文档程序为例

新建一个MFC单文档程序,如GdiPlus,在右击项目,选择 属性--> Input-->Additional Dependencies ,在其中添加 gdiplus.lib

2. 包含头文件

在 stdafx.h 中 添加如下语句

#include <GdiPlus.h>using namespace Gdiplus;
3. 初始化GDI+

在使用GDI+之前,要初始化GDI+

在CGdiPlusApp类中添加两个变量

GdiplusStartupInput m_GdiplusStartupInput;ULONG_PTR m_GdiplusToken;
在InitInstance()函数中添加初始化语句

GdiplusStartup(&m_GdiplusToken,&m_GdiplusStartupInput,NULL); 

初始化GDI+完成后,就可以使用GDI+中的对象和函数,进行图像处理

4. 关闭GDI+

程序退出时,要关闭GDI+

在ExitInstance()函数中添加关闭语句

GdiplusShutdown(m_GdiplusToken);

GDI+的使用                                                                                                            

可以在CGdi_PlusView的OnDraw()函数中,使用GDI+

下面的代码实现了:

1.  基本图形的绘制

2. 创建新的Bitmap,设置并显示

3. 将一张图片透明化显示

4. 将透明的图片保存到硬盘

Graphics graph(pDC->GetSafeHdc());//--------------------------------------//绘制基本图形:直线和贝塞尔曲线Gdiplus::Pen red_pen(Color::Red,10);red_pen.SetDashStyle(DashStyleDash);Gdiplus::Point pt1(0,300);Gdiplus::Point pt2(200,200);Gdiplus::Point pt3(400,400);Gdiplus::Point pt4(600,100);graph.DrawLine(&red_pen,pt1,pt2);graph.DrawBezier(&red_pen,pt1,pt2,pt3,pt4);//---------------------------------------//创建一个bitmap,设置前十行为红色,其他行为半透明绿色,显示int nWidth = 400;int nHeight = 400;BYTE* picData = new BYTE[nWidth*nHeight*4];memset(picData,0,nWidth*nHeight*4);Bitmap bm(nWidth,nHeight,nWidth*4,PixelFormat32bppARGB,picData);//创建bitmapfor(int row=0;row<nHeight;++row){for(int col=0;col<nWidth;++col){if(row<10)//设置前十行红色,不透明{picData[row*nWidth*4+col*4+2] = 255;//RedWpicData[row*nWidth*4+col*4+3] = 255;//Alpha}else//设置其他行为绿色色,半透明{picData[row*nWidth*4+col*4+1] = 255;//GreenpicData[row*nWidth*4+col*4+3] = 125;//Alpha}}}graph.DrawImage(&bm,700,10);delete[] picData;//---------------------------------------//图像色彩处理,设置透明度Image image(L"1.jpg");float alpha =0.1;//原图的10%ColorMatrix cm = {1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,alpha,0,0,0,0,0,1};ImageAttributes imageAttr;imageAttr.SetColorMatrix(&cm);int w = image.GetWidth()/3;int h = image.GetHeight()/3;Bitmap bm1(w,h);Rect rect(0,0,w,h);Graphics g(&bm1);g.DrawImage(&image,rect,0,0,w,h,UnitPixel,&imageAttr);//将image绘制到bitmap中graph.DrawImage(&image,0,400,0,0,w,h,UnitPixel);//原始图像,缩放9倍 [左上角(0,400)]graph.DrawImage(&bm1,w,400);//透明10%//--------------------------------------//图像保存//获取编码器的CLSID [class id]UINT num=0;//图像编码器的数量UINT size=0;//图像编码器数组的字节数CLSID encoderClsid;ImageCodecInfo* pICI=NULL;GetImageEncodersSize(&num,&size);//获得系统编码器的数量和大小if(size==0) return;//失败pICI = (ImageCodecInfo*)(malloc(size));//编码器if(pICI==NULL) return;//失败GetImageEncoders(num,size,pICI);//获取编码器信息for(int j=0;j<num;++j){if(wcscmp(pICI[j].MimeType,L"image/png")==0)//jpeg bmp gif tiff png{encoderClsid = pICI[j].Clsid;}}free(pICI);bm1.Save(L"tranparentPic.png",&encoderClsid);//只有png才能保存下来透明信息



效果如下:






原创粉丝点击