基于MFC实现图片裁剪
- 一、引言
实现图片裁剪有多种方式,集大成者首推OpenCV,这仅介绍MFC的实现方法,即使用相关类库完成图片的裁剪。
- 二、开发环境
操作系统:windows7
IDE:vs2015
- 三、源码解析
(1).新建MFC项目,并在对话框的头文件中添加相关文件引用和函数声明。
1 #include<string> 2 #include<gdiplus.h> 3 #pragma comment(lib, "gdiplus.lib") 4 using namespace Gdiplus;
1 /********************************************* 2 **GetCutPic@函数名,矩形剪切图片 3 **pFilename@文件路径 4 **iCutStartPosX@横向剪切的起点 5 **iCutStartPosY@纵向剪切的起点 6 **iCutWidth@剪切的宽度 7 **iCutHeight@剪切的高度 8 **返回std::string@完成剪切的图片数据 9 **********************************************/ 10 std::string GetCutPic(const char *pFilename,int iCutStartPosX, int iCutStartPosY, int iCutWidth, int iCutHeight);
(2).在实现文件中,添加函数的具体源码。
1 std::string CCutPictureDemoDlg::GetCutPic(const char *pFilename, int iCutStartPosX, int iCutStartPosY, int iCutWidth, int iCutHeight) 2 { 3 CImage imgSrc, imgDest; 4 5 long lRet = imgSrc.Load(pFilename); //加载图片 6 if (lRet != 0)//加载失败 7 return ""; 8 9 //int iSrcWidth = imgSrc.GetWidth(); 10 //int iSrcHeight = imgSrc.GetHeight(); 11 imgDest.Create(iCutWidth, iCutHeight, imgSrc.GetBPP()); // 创建一个目标存储对象 12 imgSrc.BitBlt(imgDest.GetDC(), 0, 0, iCutWidth, iCutHeight, iCutStartPosX, iCutStartPosY, SRCCOPY); //COPY原图的一半到目标对象里 13 14 IStream *pStm = NULL; 15 HGLOBAL hGlobal = GlobalAlloc(GMEM_MOVEABLE, 0); 16 HRESULT hr = CreateStreamOnHGlobal(hGlobal, TRUE, &pStm); 17 18 imgDest.Save(pStm, ImageFormatJPEG); 19 20 LARGE_INTEGER liBeggining = { 0 }; 21 pStm->Seek(liBeggining, STREAM_SEEK_SET, NULL); 22 DWORD size = GlobalSize(hGlobal); 23 LPBYTE lpData = (LPBYTE)GlobalLock(hGlobal); 24 25 std::string strDestBuf; 26 strDestBuf.append((const char*)lpData, size); 27 28 pStm->Release(); 29 GlobalFree(hGlobal); 30 31 imgDest.ReleaseDC(); // 释放资源 32 imgDest.Destroy(); // 销毁资源 33 34 return strDestBuf; 35 }
(3).测试函数的调用。
1 std::string strPicBuf = GetCutPic("f:\\1.jpg", 200, 200, 400, 400);
- 四、结语
经验证,基于MFC技术开发可实现图片的裁剪,此文仅做技术探讨,如有疑问请联系我,微信:790569043。

浙公网安备 33010602011771号