利用MFC和GDI+给图像指定位置加上汉字

来源:互联网 发布:安卓模拟器软件 编辑:程序博客网 时间:2024/06/06 01:26

OpenCV不支持在图像上叠加中文汉字,网上查到很多方法,包括修改Opencv函数的等,以下方法在XP、VC6.0中证实方便有效。就是需要先安装GDI+软件包。

以下仅是核心代码,还需要遵守GDI+一般使用过程,即先完成GDI+安装及其在VC中配置,使用前要进行初始化等。

请参照百度网页中步骤:http://hi.baidu.com/cannotforget/item/30769034f08c35f72784f4dd

程序核心代码:

Image  image( L"IMG_3143.JPG" );             //加载原图,格式可以有很多种,具体查GDI+
 
 Graphics imageGraphics( &image );            //通过Image对象创建一个绘图句柄,注意,这个绘图句柄只要一操作,就是在Image上进行操作
 
 imageGraphics.SetTextRenderingHint( TextRenderingHintAntiAlias );
 WCHAR string[ ] = L"这是F-35!";             //你要写上去的文字,注意文字的个数,由于是WCHAR类型,所以汉字和英文都占两个字节,例子中个数为7
 
 Font myFont( L"黑体", 56 );                  //设置字体
 PointF origin( 200.0f, 30.0f );              //绘制文字的起始位置
 SolidBrush blackBrush( Color( 255, 255, 0, 0 ) ); //文字的颜色//颜色可以设置为半透明等,只要更改Color的第一个参数,0为绝对透明,255为不透明
 StringFormat format;                         //设置文本排列方式
 format.SetAlignment( StringAlignmentCenter );//居中
 
 imageGraphics.DrawString( string, 7, &myFont, origin, &format, &blackBrush ); //用图像绘图句柄绘制文字,相当于在图片上打上文字//注意文字长度,不能大于7不然后面为乱码
 
 WCHAR Astring[ ] = L"【半透明文字!】";
 Font AmyFont( L"黑体", 88 );                   //设置字体
 PointF Aorigin( 400.0f, 100.0f );              //绘制文字的起始位置
 SolidBrush AblackBrush( Color( 32, 0, 255, 0 ) ); //文字的颜色//颜色可以设置为半透明等,只要更改Color的第一个参数,0为绝对透明,255为不透明
 StringFormat Aformat;                         //设置文本排列方式
 Aformat.SetAlignment( StringAlignmentCenter );//居中
 
 imageGraphics.DrawString( Astring, 8, &AmyFont, Aorigin, &Aformat, &AblackBrush );
 
 CLSID pngClsid;
 GetEncoderClsid( L"image/jpeg", &pngClsid );
 image.Save( L"Mosaic2.JPG", &pngClsid, NULL );//保存更改后的图像

程序关键函数:

int GetEncoderClsid(const WCHAR* format, CLSID* pClsid)
{
 UINT  num = 0;          // number of image encoders
 UINT  size = 0;         // size of the image encoder array in bytes
 
 ImageCodecInfo* pImageCodecInfo = NULL;
 
 GetImageEncodersSize(&num, &size);
 if(size == 0)
  return -1;  // Failure
 
 pImageCodecInfo = (ImageCodecInfo*)(malloc(size));
 if(pImageCodecInfo == NULL)
  return -1;  // Failure
 
 GetImageEncoders(num, size, pImageCodecInfo);
 
 for(UINT j = 0; j < num; ++j)
 {
  if( wcscmp(pImageCodecInfo[j].MimeType, format) == 0 )
  {
   *pClsid = pImageCodecInfo[j].Clsid;
   free(pImageCodecInfo);
   return j;  // Success
  }   
 }
 
 free(pImageCodecInfo);
 return -1;  // Failure
}

【致谢】http://bbs.csdn.net/topics/380229839