CImage类使用
前言
CImage类是基于GDI+的,但是这里为什么要讲归于GDI?
主要是基于这样的考虑: 在GDI+环境中,我们可以直接使用GDI+ ,没多少必要再使用CImage类
但是,如果再GDI环境中,我们要想使用GDI+,有点麻烦,还得加入头文件,加入启动GDI+的代码和关闭GDI+的代码,显得太罗嗦了,GDI 的CBitmap 处理功能又有局限,只能处理BMP格式的图片。 怎么办?这时,我们便可使用CImage类,因为这个类本身封装了GDI+得使用环境,所以无需我们手动设置,简化了我们的操作。 同时,又可以利用GDI+中强大的图片处理功能,及可以简便的与CBitmap对象进行转换 ,大大方便了在GDI环境下,进行各种图片处理工作 。
其实,将其称作 GDI/ GDI+ 混合编程,这样才更确切些。
为什么引入CImage类?
CBitmap 类只能处理BMP格式的图片,非常受限。
而CImage可以处理JPGE GIF BMP PNG多种格式图片,扩展了图片处理功能 且能与CBitmap 进行转换( 因为所载入的位图句柄都是HBITMAP,所以可相互转换),因此引入CImage类进行图像处理
CImage provides enhanced bitmap support, including the ability to load and save images in JPEG, GIF, BMP, and Portable Network Graphics (PNG) formats
CImage类介绍
CImage是MFC和ATL共享的新类,它能从外部磁盘中调入一个JPEG、GIF、BMP和PNG格式的图像文件加以显示,而且这些文件格式可以相互转换。
CImage是VC.NET中定义的一种MFC/ATL共享类,也是ATL的一种工具类,它提供增强型的(DDB和DIB)位图支持,可以装入、显示、转换和保存多种格式的图像文件,包括BMP、GIF、JPG、PNG、TIF等。CImage是一个独立的类,没有基类。(CImage类是基于GDI+的,从VC.Net起引进,VC 6.0中没有。)
ATL(Active Template Library,活动模板库)是一套基于模板的 C++ 类,用以简化小而快的 COM 对象的编写。
为了在MFC程序中使用CImage类,必须包含ATL的图像头文件atlimage.h:(在VS08 SP1中不用包含)
#include <atlimage.h>
1 加载位图文件
- // CImage可加载的图片文件有JPG,BMP,TIF.PNG等格式 而CBitmap只能加载BMP图片文件
- if(!PathFileExists(imgFilePath))
- return NULL;
- CImage nImage;
- nImage.Load(imgFilePath);
- return nImage.Detach(); //返回HBITMAP 可用CBitmap 处理 也可用CImage处理
2 与CBitmap转换
- CImage nImage;
- nImage.Load(imgFilePath);
- HBITMAP hBitmap=nImage.Detach(); // 获得位图句柄 用以转换
- // 转换方式一:
- CBitmap bmp;
- bmp.DeleteObject();
- bmp.Attach(hBitmap); // 转换为CBitmap对象
- // 转换方式二:
- CBitmap *pBitmap=CBitmap::FromHandle(nImage.m_hBitmap);
3 获得CImage对象的cdc
- CDC *pDC=CDC::FromHandle(nImage.GetDC());
- // Use pDC here
- nImage.ReleaseDC();
4 显示位图
思路: 将CImage对象 绘制在对应的DC中
所使用的函数 BitBlt StretchBlt Draw等
以Draw举例:
- BOOL Draw(
- HDC hDestDC,
- int xDest,
- int yDest,
- int nDestWidth,
- int nDestHeight,
- int xSrc,
- int ySrc,
- int nSrcWidth,
- int nSrcHeight
- ) const throw( );
- BOOL Draw(
- HDC hDestDC,
- const RECT& rectDest,
- const RECT& rectSrc
- ) const throw( );
- BOOL Draw(
- HDC hDestDC,
- int xDest,
- int yDest
- ) const throw( );
- BOOL Draw(
- HDC hDestDC,
- const POINT& pointDest
- ) const throw( );
- BOOL Draw(
- HDC hDestDC,
- int xDest,
- int yDest,
- int nDestWidth,
- int nDestHeight
- ) const throw( );
- BOOL Draw(
- HDC hDestDC,
- const RECT& rectDest
- ) const throw( );
Draw performs the same operation as StretchBlt, unless the image contains a transparent color or alpha channel. In that case,Draw performs the same operation as eitherTransparentBlt orAlphaBlend as required.
For versions of Draw that do not specify a source rectangle, the entire source image is the default. For the version ofDraw that does not specify a size for the destination rectangle, the size of the source image is the default and no stretching or shrinking occurs.
EXAMPLE 1:
- CImage img;
- img.Load("1.jpg");
- if (!img.IsNull())
- {
- img.Draw(pDC->m_hDC,CRect(0,0,100,100));
- }
EXAMPLE 2: 画在另一个位图中
- CImage img;
- img.Load(filePath);
- // 获得CImage对象的 CDC
- HDC hDC=img.GetDC();
- CDC *pDC=CDC::FromHandle(hDC);
- CBitmap bmp;// 只是创建了位图对象,但还没有将位图对象与位图资源联系起来
- bmp.CreateCompatibleBitmap(pDC,nWidth,nHeight); // 创建新的位图资源
- CDC memDC;
- memDC.CreateCompatibleDC(pDC);
- CBitmap *pOld=memDC.SelectObject(&bmp);
- // 将img图像绘制到bmp中
- ::SetStretchBltMode(memDC.m_hDC,HALFTONE);
- ::SetBrushOrgEx(memDC.m_hDC,0,0,NULL);
- img.StretchBlt(memDC.m_hDC,CRect(0,0,nWidth,nHeight)/*DestRect*/,CRect(0,0,nWidth,nHeight)/*SourceRect*/,SRCCOPY);
- HBITMAP hBitmap=(HBITMAP)memDC.SelectObject(pOld->m_hObject); // 获得新创建的位图资源句柄
- img.ReleaseDC();
5 将位图资源与对象进行分离
- inline HBITMAP CImage::Detach() throw()
- {
- HBITMAP hBitmap;
- ATLASSUME( m_hBitmap != NULL );
- ATLASSUME( m_hDC == NULL );
- hBitmap = m_hBitmap;
- m_hBitmap = NULL;
- m_pBits = NULL;
- m_nWidth = 0;
- m_nHeight = 0;
- m_nBPP = 0;
- m_nPitch = 0;
- m_iTransparentColor = -1;
- m_bHasAlphaChannel = false;
- m_bIsDIBSection = false;
- return( hBitmap );
- }
6 释放资源
CBitmap 使用DeleteObject()来主动释放掉位图资源
CImage 没有DeleteObject()函数 ,而是用Destroy()函数来主动释放位图资源
- inline void CImage::Destroy() throw()
- {
- HBITMAP hBitmap;
- if( m_hBitmap != NULL )
- {
- hBitmap = Detach();
- ::DeleteObject( hBitmap ); //释放位图资源
- }
- }
CBitmap 析构时,会自动释放掉所占用的位图资源
CImage 析构时,也会自动释放掉所占用的位图资源
- inline CImage::~CImage() throw()
- {
- Destroy(); //释放掉所占用的位图资源
- s_initGDIPlus.DecreaseCImageCount();
- }
7 读写图像数据
主要用到3个函数 :
1 )GetBits() 获得数据区的指针
Retrieves a pointer to the actual bit values of a given pixel in a bitmap.
void* GetBits( ) throw( ); |
- inline void* CImage::GetBits() throw()
- {
- ATLASSUME( m_hBitmap != NULL );
- ATLASSERT( IsDIBSection() );
- return( m_pBits );
- }
A pointer to the bitmap buffer. If the bitmap is a bottom-up DIB, the pointer points near the end of the buffer. If the bitmap is a top-down DIB, the pointer points to the first byte of the buffer.
Using this pointer, along with the value returned by GetPitch, you can locate and change individual pixels in an image.
注意: 由GetBits()取得的指针不一定是图片数据的起始行,必须结合GetPitch()的值来确定起始行位置
2)GetPitch()
- inline int CImage::GetPitch() const throw()
- {
- ATLASSUME( m_hBitmap != NULL );
- ATLASSERT( IsDIBSection() );
- return( m_nPitch );
- }
获得图像数据每一行的字节数
The pitch of the image. If the return value is negative, the bitmap is a bottom-up DIB and its origin is the lower left corner. If the return value is positive, the bitmap is a top-down DIB and its origin is the upper left corner.
GetBits 与 GetPitch 关系:
当GetPitch()<0时,GetBits()获得的指针指向最后一行
当GetPitch()>0时,GetBits()获得的指针指向第一行
图像数据首行地址:
- BYTE *pData=NULL;
- if(img.GetPitch()<0)
- pData=(BYTE*)img.GetBits()+(img.GetPitch()*(img.GetHeight()-1));
- else
- pData=(BYTE*)img.GetBits();
或
- BYTE *pData=NULL;
- if(img.GetPitch()<0)
- pData=(BYTE *)img.GetPixelAddress(img.GetHeight()-1,0);
- else
- pData=(BYTE *)img.GetPixelAddress(0,0);
3)GetBPP() 返回每个像素所占的bit数
- inline int CImage::GetBPP() const throw()
- {
- ATLASSUME( m_hBitmap != NULL );
- return( m_nBPP );
- }
The number of bits per pixel.
This value determines the number of bits that define each pixel and the maximum number of colors in the bitmap
一个综合例子:
- void CMyImage::Negatives(void)
- {
- int i, j;
- //图像每一行的字节数
- int nRowBytes = GetPitch();
- int nWidth = GetWidth();
- int nHeight = GetHeight();
- //每个像素所占的字节数
- int nClrCount = GetBPP() / 8;
- LPBYTE p;
- for(int index = 0; index < nClrCount; index++)
- {
- p = (LPBYTE)GetBits();
- for(i = 0; i < nHeight; i++)
- {
- for(j = 0; j < nWidth; j++)
- {
- p[j*nClrCount + index] = 255 - p[j*nClrCount + index];
- }
- //如果nRowBytes>0 则从开始到结尾
- //如果nRowBytes<0, 则从结尾到开始
- p += nRowBytes;
- }
- }
- }
8 保存到图像文件中
Saves an image as the specified file name and type.
HRESULT Save( |
- inline HRESULT CImage::Save( LPCTSTR pszFileName, REFGUID guidFileType ) const throw()
- {
- if( !InitGDIPlus() )
- {
- return( E_FAIL );
- }
- UINT nEncoders;
- UINT nBytes;
- Gdiplus::Status status;
- status = Gdiplus::GetImageEncodersSize( &nEncoders, &nBytes );
- if( status != Gdiplus::Ok )
- {
- return( E_FAIL );
- }
- USES_CONVERSION_EX;
- Gdiplus::ImageCodecInfo* pEncoders = static_cast< Gdiplus::ImageCodecInfo* >( _ATL_SAFE_ALLOCA(nBytes, _ATL_SAFE_ALLOCA_DEF_THRESHOLD) );
- if( pEncoders == NULL )
- return E_OUTOFMEMORY;
- status = Gdiplus::GetImageEncoders( nEncoders, nBytes, pEncoders );
- if( status != Gdiplus::Ok )
- {
- return( E_FAIL );
- }
- CLSID clsidEncoder = CLSID_NULL;
- if( guidFileType == GUID_NULL )
- {
- // Determine clsid from extension
- clsidEncoder = FindCodecForExtension( ::PathFindExtension( pszFileName ), pEncoders, nEncoders );
- }
- else
- {
- // Determine clsid from file type
- clsidEncoder = FindCodecForFileType( guidFileType, pEncoders, nEncoders );
- }
- if( clsidEncoder == CLSID_NULL )
- {
- return( E_FAIL );
- }
- LPCWSTR pwszFileName = T2CW_EX( pszFileName, _ATL_SAFE_ALLOCA_DEF_THRESHOLD );
- #ifndef _UNICODE
- if( pwszFileName == NULL )
- return E_OUTOFMEMORY;
- #endif // _UNICODE
- if( m_bHasAlphaChannel )
- {
- ATLASSUME( m_nBPP == 32 );
- Gdiplus::Bitmap bm( m_nWidth, m_nHeight, m_nPitch, PixelFormat32bppARGB, static_cast< BYTE* >( m_pBits ) );
- status = bm.Save( pwszFileName, &clsidEncoder, NULL );
- if( status != Gdiplus::Ok )
- {
- return( E_FAIL );
- }
- }
- else
- {
- Gdiplus::Bitmap bm( m_hBitmap, NULL );
- status = bm.Save( pwszFileName, &clsidEncoder, NULL );
- if( status != Gdiplus::Ok )
- {
- return( E_FAIL );
- }
- }
- return( S_OK );
- }
- pStream
-
A pointer to a stream containing the file name for the image.
- pszFileName
-
A pointer to the file name for the image.
- guidFileType
-
The file type to save the image as. Can be one of the following:
ImageFormatBMP An uncompressed bitmap image.
ImageFormatPNG A Portable Network Graphic (PNG) compressed image.
ImageFormatJPEG A JPEG compressed image.
ImageFormatGIF A GIF compressed image.
Call this function to save the image using a specified name and type. If the guidFileType parameter is not included, the file name's file extension will be used to determine the image format. If no extension is provided, the image will be saved in BMP format.
MSDN例子:
- Copy Code
- // Demonstrating saving various file formats
- int _tmain(int argc, _TCHAR* argv[])
- {
- CImage myimage;
- // load existing image
- myimage.Load("image.bmp");
- // save an image in BMP format
- myimage.Save("c:\image1.bmp");
- // save an image in BMP format
- myimage.Save("c:\image2",ImageFormatBMP);
- // save an image in JPEG format
- myimage.Save("c:\image3.jpg");
- // save an image in BMP format, even though jpg file extension is used
- myimage.Save("c:\image4.jpg",ImageFormatBMP);
- return 0;
- }
9 应用实例: 将两个图像合并为一个新的图像
- //图像路径
- CString img1Path;
- CString img2Path;
- CString img3Path;
- img1Path=_T("1.bmp");
- img2Path=_T("2.bmp");
- img3Path=_T("3.bmp"); // 将 图片1、2 合并成图片3
- CImage img1,img2,img3;
- img1.Load(img1Path);
- img2.Load(img2Path);
- CBitmap bmp;
- CDC memDC;
- HDC hDC=NULL;
- CDC *pDC=NULL;
- CBitmap *pOld=NULL;
- HBITMAP hBitmap=NULL;
- //创建位图
- hDC=img1.GetDC();
- pDC=CDC::FromHandle(hDC);
- bmp.DeleteObject();
- bmp.CreateCompatibleBitmap(pDC,img1.GetWidth()/2,img1.GetHeight());
- memDC.DeleteDC();
- memDC.CreateCompatibleDC(pDC);
- pOld=memDC.SelectObject(&bmp);
- ::SetStretchBltMode(memDC.m_hDC,HALFTONE);
- ::SetBrushOrgEx(memDC.m_hDC,0,0,NULL);
- // 背景置白色
- CRgn rectRgn;
- rectRgn.CreateRectRgn(0,0,img1.GetWidth()/2,img1.GetHeight());
- CBrush brush;
- brush.CreateSolidBrush(RGB(255,255,255));
- memDC.FillRgn(&rectRgn,&brush);
- //画图
- img1.StretchBlt(memDC.m_hDC,CRect(0,0,img1.GetWidth()/2,img1.GetHeight()/2),CRect(0,0,img1.GetWidth(),img1.GetHeight()),SRCCOPY);
- img2.StretchBlt(memDC.m_hDC,CRect(0,img1.GetHeight()/2,img1.GetWidth()/2,img1.GetHeight()),CRect(0,0,img2.GetWidth(),img2.GetHeight()),SRCCOPY);
- hBitmap=(HBITMAP)memDC.SelectObject(pOld->m_hObject);
- img3.Attach(hBitmap);// 载入位图资源
- img3.Save(img3Path); // 保存新的位图
- img1.ReleaseDC();
- img1.Destroy();
- img2.Destroy();
- img3.Destroy();
CImage类使用的更多相关文章
- 强大的CImage类
这下有了CImage类,处理其他类型的图片不再寻找第三方类库了.加载到对话框背景的代码如下: //从资源里载入背景JPEG图片 HRSRC hRsrc=::FindResource(AfxGetRe ...
- 用CImage类来显示PNG、JPG等图片
系统环境:Windows 7软件环境:Visual Studio 2008 SP1本次目的:实现VC单文档.对话框程序显示图片效果 CImage 是VC.NET中定义的一种MFC/ATL共享类,也是A ...
- CImage类的介绍与使用
CImage类的介绍与使用 程序代码下载处:http://download.csdn.net/source/2098910 下载处:http://hi.baidu.com/wangleitongxin ...
- c++ 中CImage类Load函数,路径中含有空格应对策略!
最近,在写一些东西的时候,需要用到CImage类将JPG各式的图片转换成BMP图片,传入的是图片的绝对地址:如C:\Users\Administrator\Documents\Visual Studi ...
- GDI 总结三: CImage类使用
前言 CImage类是基于GDI+的.可是这里为什么要讲归于GDI? 主要是基于这种考虑: 在GDI+环境中,我们能够直接使用GDI+ ,没多少必要再使用CImage类 可是,假设再 ...
- CImage类
CImage封装了DIB(设备无关位图)的功能,因而可以让我们能够处理每个位图像素.这里介绍GDI+和CImage的一般使用方法和技巧. TAG: GDI CImage 后处理 我们知道,Vi ...
- GDI+ 两个汇总 : 为什么CImage类别是根据GDI+的?
在很多资料上都说CImage类是基于GDI+的,可是为什么是基于GDI+的呢? 由于使用这个类时,并没有增加#include <gdiplus.h> .也没有在程序開始和结束时分别写GDI ...
- 供CImage类显示的半透明PNG文件处理方法
原文链接: http://blog.sina.com.cn/s/blog_4070692f010003gy.html 前补:没想到这个帖子好像挺多人看哪……看来大家都被这个png郁闷的够呛.显示p ...
- CImage类提供了GetBits()函数原理及实现
CImage类提供了GetBits()函数来读取数据区,GetBits()函数返回的是图片最后一行第一个像素的地址,网上有人说返回指针的起始位置是不同的,有些图片返回的是左上角像素的地址,有些是左下角 ...
- c++ MFC图像处理CImage类常用操作代码
原文作者:aircraft 原文地址:https://www.cnblogs.com/DOMLX/p/9598974.html MFC图像处理CImage类常用操作 CImage类头文件为#inclu ...
随机推荐
- vue封装组件
父组件 <template> <view> <assembly @submitToParent="submitToParent"> <te ...
- Web开发的常用攻击和防御方式
一.XSS 主要利用:1.盲目相信用户提交的内容 2.直接把用户的字符串转化成DOM 分类: 1.存储型XSS,恶意脚本存在数据库中,所有访问页面的用户都会被攻击 2.反射型XSS,脚本写在URL中, ...
- 15. 测试环境部署-linux
抽奖项目部署文档: 1.抽奖项目使用python3开发,python版本3.x都可以 需要安装的python第三方模块 pip install django==1.9.0 这个一定要加版本号 pip ...
- java spring 理解
1.spring IOC容器 其实就是 new 了一个 ApplicationContext 类对象.->应用上下文对象. 2.应用上下文对象 实例化.配置,并管理 bean. 所以上下文对象是 ...
- Linux学习 --- 系统网络配置
前言 : 如果一台计算机想接入互联网,必须配置好IP地址,子网掩码,网关,DNS服务器.在Linux系统中,这些信息都可以修改对应的配置文件来进行配置.临时配置一下网络可以使用一些简单的命令来进行配置 ...
- React使用高阶组件与Hooks实现权限拦截教程
导读 高阶组件就是接受一个组件作为参数并返回一个新组件(功能增强的组件)的函数.这里需要注意高阶组件是一个函数,并不是组件,这一点一定要注意,本文给大家分享React高阶组件使用小结,一起看看吧 高阶 ...
- (0409) Pycharm 的设置--参数设置(运行.py文件带参数,例如argument) 比如: demo.py -prj xxx
1) https://www.cnblogs.com/yksgzlyh/p/10221960.html 点击"Run"菜单下的"Edit Configurations. ...
- IDEA 项目运行内存设置
IDEA 运行内存设置 1.堆内存设置 2.help ---- edit custom VM options 参考摘录:https://blog.csdn.net/wentaolv/article/d ...
- MySQL 5.7升级8.0过程(详解)
记一次MySQL 5.7升级8.0的详细过程,聊聊我的思路,希望可以帮助大家. 以一个例子为切入点 一.升级背景 为什么要升级到MySQL8.0?大概多久进行一次? 大家可以参考下图记录的各个版本的发 ...
- 吴恩达老师机器学习课程chapter08——降维
吴恩达老师机器学习课程chapter08--降维 本文是非计算机专业新手的自学笔记,高手勿喷. 本文仅作速查备忘之用,对应吴恩达(AndrewNg)老师的机器学期课程第十四章. 本章节只有结论,没有任 ...