MFC GDI+ 图片上写文字

本文介绍了如何在MFC应用程序中利用GDI+库将文字添加到图片上。首先进行GDI+的初始化,然后加载图片并创建Graphics对象以在图片上绘制。接着设置文字的字体、大小、颜色和排列方式,并调用DrawString方法将文字绘制到图片上。最后,保存修改后的图像文件。

开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

声明

#include "afxdtctl.h" 

#include <GdiPlus.h>
#pragma comment(lib, "GdiPlus.lib")
using namespace Gdiplus;

全局变量

static ULONG_PTR m_gdiplusToken;

 

初始化

  Gdiplus::GdiplusStartupInput gdiplusStartupInput;
    Gdiplus::GdiplusStartup(&m_gdiplusToken, &gdiplusStartupInput, NULL);

Gdiplus::GdiplusShutdown(m_gdiplusToken);

 

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
}
 

开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值