【问题标题】:How to create a PNG image with custom fonts from text如何使用文本中的自定义字体创建 PNG 图像
【发布时间】:2021-06-11 18:34:45
【问题描述】:

我正在用 C 语言编写一个程序,它将文本作为用户输入并生成 png 图像作为输出,并以自定义字体呈现相同的文本。

我知道 C 语言没有用于图形的标准库,因此我试图找出最适合初学者开发人员使用的库。

我的操作系统是 Ubuntu,我想做 CLI 工具

例如https://github.com/matsuyoshi30/germanium

【问题讨论】:

  • 如果您自己编写代码没有教学上的原因,您可以在 CLI 中使用 ImageMagick 来完成,例如制作一张 640x480 的红色图片并用白色文字注释magick -size 640x480 xc:red -fill white -annotate +10+20 "This is some text" result.png
  • 如果您可以将船推向 C++,您可以在cimg.eu 使用 CImg

标签: c linux image graphics png


【解决方案1】:

对于这么简单的需求,你可以使用cairo,只需调整png大小和字体:

#include <cairo.h>

int main(void)
{
    cairo_surface_t *surface;
    cairo_t *cr;

    surface = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 250, 50);
    cr = cairo_create(surface);

    cairo_set_source_rgb(cr, 0, 0, 0);
    cairo_select_font_face(cr, "Sans", CAIRO_FONT_SLANT_NORMAL,
      CAIRO_FONT_WEIGHT_NORMAL);
    cairo_set_font_size(cr, 40.0);

    cairo_move_to(cr, 10.0, 35.0);
    cairo_show_text(cr, "Hello world!");

    cairo_surface_write_to_png(surface, "image.png");

    cairo_destroy(cr);
    cairo_surface_destroy(surface);

    return 0;
}

因为你在 ubuntu 上:

sudo apt-get install -y libcairo2-dev

并编译:

gcc demo.c -o demo `pkg-config --cflags --libs cairo`

对于更复杂的用途,你应该将cairo与pango结合起来:

https://fossies.org/linux/pango/examples/cairosimple.c

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-29
    • 2018-08-29
    • 1970-01-01
    • 1970-01-01
    • 2019-04-12
    • 2018-06-24
    • 2011-01-20
    相关资源
    最近更新 更多