1.初始化:
#include <GdiPlus.h> using namespace Gdiplus; #pragma comment(lib,"gdiplus.lib")
GdiplusStartupInput gdiplusStartupInput; GdiplusStartup(&Gdi_token, &gdiplusStartupInput, NULL) ;
GdiplusShutdown(Gdi_token);
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()); }
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; }