GDI+使用小记

1.初始化:

#include <GdiPlus.h>
using namespace Gdiplus; 
#pragma comment(lib,"gdiplus.lib")

 GdiplusStartupInput gdiplusStartupInput;
	GdiplusStartup(&Gdi_token, &gdiplusStartupInput, NULL) ;

  GdiplusShutdown(Gdi_token);

2.使用:
先贴几个简单的例子:

绝对路径:

		    Image image(TEXT("D:\\Program Files\\vs2005_Project\\test\\test\\res\\未标题-1.png"));
			CPaintDC dc(this);
			Graphics g(dc) ;
			g.DrawImage(&image,0,0,image.GetWidth(),image.GetHeight());


不要写Image img;这样会报错:error C2248: “Gdiplus::Image::Image”: 无法访问 protected 成员(在“Gdiplus::Image”类中声明)

相对路径:
  

BOOL LoadResImage(int nResID,Image * &lpImage,LPCTSTR lpType = TEXT("PNG"));
BOOL LoadResImage(int nResID,Image * &lpImage, LPCTSTR lpType)
{
	HINSTANCE hIns=AfxGetInstanceHandle();
	HRSRC hRsrc = ::FindResource (hIns,MAKEINTRESOURCE(nResID),lpType); // type 
	if (!hRsrc) 
		return FALSE; 
	// load resource into memory 
	DWORD len = SizeofResource(hIns, hRsrc); 
	BYTE* lpRsrc = (BYTE*)LoadResource(hIns, hRsrc); 
	if (!lpRsrc) 
		return FALSE; 
	// Allocate global memory on which to create stream 
	HGLOBAL m_hMem = GlobalAlloc(GMEM_FIXED, len); 
	//HGLOBAL m_hMem = GlobalAlloc(GHND, len); 
//=======================================================
//GMEM_FIXED:分配固定的内存
//GMEM_MOVEABLE:分配可移动的内存,不能与 GMEM_FIXED 组合使用
//GMEM_ZEROINIT:将所申请内存初始化为0.
//=======================================================
	BYTE* pmem = (BYTE*)GlobalLock(m_hMem); 
	memcpy(pmem,lpRsrc,len); 
	IStream* pstm; 
	HRESULT ht =  CreateStreamOnHGlobal(m_hMem,FALSE,&pstm); 
	if (ht != S_OK)
	{
		GlobalFree(m_hMem);
		return FALSE ;
	}
	// load from stream 
	lpImage=Gdiplus::Image::FromStream(pstm); 
	// free/release stuff 
	GlobalUnlock(m_hMem); 
	pstm->Release(); 
	FreeResource(lpRsrc);
         GlobalFree(m_hMem);return TRUE ;
}

调用:
Image *pimage;
            //BOOL result  = LoadResImage(IDR_JPG1,pimage,TEXT("JPG")) ;
			BOOL result  = LoadResImage(IDB_PNG1,pimage,TEXT("PNG")) ;
			if (result)
			{
				CPaintDC dc(this);
				Graphics g(dc) ;
				g.DrawImage(pimage,0,0,pimage->GetWidth(),pimage->GetHeight());
			}

小知识:要用PS创建背景透明的PNG,直接把背景删了,保存。同样,上面例子画出来的PNG透明部分会把底色透出来


3.判断Image对象的类型:
简单说明例子:

	                        GUID formatID;
				pimage->GetRawFormat(&formatID);
				int m_nImgFormat;
				enum IMGFORMAT { if_bmp, if_jpg, if_png, if_gif, if_tiff, if_error };
				if (formatID == Gdiplus::ImageFormatBMP)
				{
					m_nImgFormat = if_bmp;
				}
				if (formatID == Gdiplus::ImageFormatJPEG)
				{
					m_nImgFormat = if_jpg;
				}
				if (formatID == Gdiplus::ImageFormatPNG)
				{
					m_nImgFormat = if_png;
				}
				if (formatID == Gdiplus::ImageFormatGIF)
				{
					m_nImgFormat = if_gif;
				}
				if (formatID == Gdiplus::ImageFormatTIFF)
				{
					m_nImgFormat = if_tiff;
				}


你可能感兴趣的:(Stream,image,token,byte,tiff,GDI+)