1. 引入GDI++
stdafx.h
//...
typedef unsigned long ULONG_PTR, *PULONG_PTR;
#include <Gdiplus.h>
using namespace Gdiplus;
#pragma comment (lib, "GdiPlus.lib")
static ULONG_PTR m_pGdiToken;
static struct GdiplusStartupInput m_gdiplusStartupInput;
//...
2.初始化 ,可以在 BOOL C*DemoApp::InitInstance() 或BOOL C*DemoDlg::OnInitDialog()中初始化
//初始化GDI+.
GdiplusStartup(&m_pGdiToken, &m_gdiplusStartupInput, NULL);
3. 打开图像和显示图片
void DrawImg2Hdc(Image *image, UINT id, CWnd* cWnd)
{
if(image==0) return;
CDC* pDC = cWnd->GetDlgItem(id)->GetDC();
CRect rect;
cWnd->GetDlgItem(id)->GetWindowRect(&rect);
Graphics graphics( pDC->m_hDC);
graphics.DrawImage(image,0,0, rect.Width(), rect.Height());
}
Image* KLoadImage(CString filename)
{
LPWSTR strjpg = new WCHAR[255];
LPTSTR lpStr2 = filename.GetBuffer( filename.GetLength() );
int nLen2 = MultiByteToWideChar(CP_ACP, 0,lpStr2, -1, NULL, NULL);
MultiByteToWideChar(CP_ACP, 0, lpStr2, -1, strjpg, nLen2);
Image *image=0;
image=Image::FromFile(strjpg,true);
//生成缩略图
//Image* thumbnailImage = image->GetThumbnailImage(10,10);
return image;
}
Bitmap* KLoadBitmap(CString filename)
{
LPWSTR strjpg = new WCHAR[255];
LPTSTR lpStr2 = filename.GetBuffer( filename.GetLength() );
int nLen2 = MultiByteToWideChar(CP_ACP, 0,lpStr2, -1, NULL, NULL);
MultiByteToWideChar(CP_ACP, 0, lpStr2, -1, strjpg, nLen2);
Bitmap *image=0;
image=Bitmap::FromFile(strjpg,true);
//生成缩略图
//Image* thumbnailImage = image->GetThumbnailImage(10,10);
return image;
}
4. 获取图像像素
unsigned char *pImageBuffer;
pImageBuffer = 0;
long BufferLen;
imageWidth = image->GetWidth();
imageHeight = image->GetHeight();
BufferLen= imageWidth * imageHeight * 3;
BitmapData bitmapData={0};
bitmapData.Stride = WIDTHSTEP(imageWidth);
bitmapData.Scan0 = new BYTE[bitmapData.Stride * imageHeight];
if(pImageBuffer!=0)
delete pImageBuffer;
pImageBuffer=new unsigned char[BufferLen];
Rect rect(0,0, imageWidth, imageHeight);
image->LockBits(&rect, ImageLockModeRead | ImageLockModeUserInputBuf,
PixelFormat24bppRGB, &bitmapData);
memcpy(pImageBuffer, (BYTE*)bitmapData.Scan0, BufferLen);
delete bitmapData.Scan0;
image->UnlockBits( &bitmapData);