1、图片的显示
// 下面是GDI+要使用的几个头文件
#ifndef ULONG_PTR
#define ULONG_PTR unsigned long*
#endif
#include "Gdiplus.h"
#include <afxole.h>
#include <Atlbase.h>
Gdiplus::GdiplusStartupInput m_gdiplusStartupInput;
ULONG_PTR m_gdiplusToken;
// 初始化GDI+库
void InitGuiPlus()
{
Gdiplus::GdiplusStartup(&m_gdiplusToken, &m_gdiplusStartupInput, NULL);
}
// 关闭GDI+库
void CleanupGuiPlus()
{
Gdiplus::GdiplusShutdown(m_gdiplusToken);
}
Gdiplus::Bitmap * m_pBmp;
// 加载图片
Gdiplus::Bitmap * LoadPic(LPCSTR szPicUrl)
{
Gdiplus::Bitmap * pBmp = NULL;
CFileFind fFind;
if (!fFind.FindFile(szPicUrl))
{
return pBmp;
}
USES_CONVERSION;
// 打开刚才浏览的图片
pBmp = new Gdiplus::Bitmap(A2W(szPicUrl));
return pBmp;
}
// 卸载图片
void UnLoadPic()
{
if (m_pBmp != NULL)
{
delete m_pBmp;
m_pBmp = NULL;
}
}
// 显示图片 (在WM_PAINT的响应处理函数对其调用)
void ShowPic(CDC *pDC, Gdiplus::Bitmap *pbmpSrc, int nSrcWidth, int nSrcHeight)
{
ASSERT(pbmpSrc != NULL);
Gdiplus::Graphics graphics(pDC->m_hDC);
graphics.DrawImage(pbmpSrc, 0, 0, nSrcWidth, nSrcHeight);
}
*************************************************************************************************
2、利用GDI+对图片缩放后保存(头文件和初始化代码同1)
// 获取图片的编码信息
BOOL GetImageEncoderCLSID( CLSID& clsid, const wchar_t* format)
{
UINT num=0, size=0;
Gdiplus::GetImageEncodersSize(&num, &size);
Gdiplus::ImageCodecInfo* pImageCodecInfo = (Gdiplus::ImageCodecInfo*)malloc(size);
if(pImageCodecInfo == NULL)
{
return FALSE;
}
Gdiplus::GetImageEncoders(num, size, pImageCodecInfo );
for( UINT i = 0; i<num; ++i )
{
if( wcscmp(pImageCodecInfo[i].MimeType, format) == 0 )
{
clsid = pImageCodecInfo[i].Clsid;
free(pImageCodecInfo);
return TRUE;
}
}
free(pImageCodecInfo);
pImageCodecInfo = NULL;
return FALSE;
}
// 按尺寸保存图片
BOOL SavePicture(LPCSTR pszFileUrl, Gdiplus::Image *pSrcBmp, int nSavedWidth, int nSavedHeight)
{
ASSERT(pSrcBmp != NULL);
// 创建预保存的图片
Gdiplus::Bitmap bmpSaved(nSavedWidth, nSavedHeight);
Gdiplus::Graphics * pGraphics = Gdiplus::Graphics::FromImage(&bmpSaved);
// 将pSrcBmp画到pGraphics中
pGraphics->DrawImage(pSrcBmp, 0, 0, nSavedWidth, nSavedHeight);
if (pGraphics == NULL)
{
return FALSE;
}
CLSID clImageClsid;
// 获取图片的编码信息
if (GetImageEncoderCLSID(clImageClsid, L"image/jpeg"))
{
USES_CONVERSION;
// 保存入片
bmpSaved.Save(A2W(pszFileUrl), &clImageClsid, NULL);
delete pGraphics;
pGraphics = NULL;
return TRUE;
}
delete pGraphics;
pGraphics = NULL;
return FALSE;
}