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

851

被折叠的 条评论
为什么被折叠?



