ImageMagick--往图片上写文字

为了在文件上写文字,话费了一天的时间,都快崩溃了,其实可以有两种写法:一种是自己实现,对指定的点进行修改像素值,一种是直接用库中的函数进行写文字;当然所有人都希望用库中的函数,既方便又好用,但是事情的发展总是不如人意,我以为我直接写一个image.annotate("abcok",Geometry("100x100"));就能实现功能,谁知道总是运行错误,调了大半天,处于崩溃边缘,于是,在Magick群里问了一下,果然有牛人给我解答,不过刚开始说的我不懂,什么是字体路径?还有就是一大串代码,一大堆英文文档。。。。好了,吐槽结束:

说重点:最重要的一个地方就是程序中:image.font("./font/n021003l.pfb");这句话。就是当时我不懂的指定字体路径。据我理解,这算是一个文字库,指定后,会把要写的文字在这里边找到对应的编码,然后显示到图片上,一般在下载的源码中,会有一个文件夹fonts(font),里边就是字体的模板,,我是把它拷贝到我的运行目录下,把这个路径指向里边的一个字体.pfb的文件。然后就可以对往图片上写文字了。

// magick_1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include 
#include 
#include 
#include 
//#pragma comment(lib,"ws2_32.lib")
using namespace std; 
using namespace Magick; 
#include 
#include 

int main(int argc,char **argv) 
{ 
  InitializeMagick(*argv);
  Image image( "test.jpg" ); 
  Blob blob;
  image.strokeColor("red"); // Outline color 
    image.strokeWidth(1);//设置画线的线宽
    image.fontPointsize(20);//设置字体的大小
  image.font("./font/n021003l.pfb");//指定字体的路径
  image.annotate("abcok",Geometry("100x100+100+100"));
  image.annotate("SouthEastGravity",SouthEastGravity);
  image.annotate("CenterGravity",CenterGravity);
  image.write("test_result.jpg");

  return 0; 
}

下边代码中实现的那个函数还没搞明白呢。

// magick_1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include 
#include 
#include 
#include 
//#pragma comment(lib,"ws2_32.lib")
using namespace std; 
using namespace Magick; 
#include 
#include 

int main(int argc,char **argv) 
{ 
  InitializeMagick(*argv);
  Image image( "test.jpg" ); 
  Blob blob;
  image.strokeColor("red"); // Outline color 
    image.strokeWidth(1);//设置画线的线宽
	image.fontPointsize(20);//设置字体的大小
  image.font("./font/n022024l.pfb");//指定字体的路径
    image.annotate("abcok",Geometry("100x100+100+100"));

  TypeMetric *ty;
  ty=new TypeMetric;

  image.fontTypeMetrics("abcok",ty);
  printf("ascent:%f\n",ty->ascent());
  printf("descent:%f\n",ty->descent());
  printf("maxHorizontalAdvance:%f\n",ty->maxHorizontalAdvance());
  printf("textHeight:%f\n",ty->textHeight());
  printf("textWidth:%f\n",ty->textWidth());
  char buf[100];
  gets(buf);
  //image.annotate("abcok",Geometry("100x100+100+100"));
  //image.annotate("SouthEastGravity",SouthEastGravity);
  //image.annotate("CenterGravity",CenterGravity);
  
  image.write("test_result.jpg");

  delete ty;
  ty=NULL;

  return 0; 
}





你可能感兴趣的:(ImageMagick)