2

I am making a program in C which will take a text as a user input and produce a png image as an output with the same text rendered in custom fonts.

I know that C doesn't have standard libraries for graphics, so I am trying to identify what is the most efficient library to use for beginner developers.

My Operating system is Ubuntu and I want to make CLI tool

For example https://github.com/matsuyoshi30/germanium

Golu
  • 350
  • 2
  • 14
  • see this https://github.com/matsuyoshi30/germanium – Golu Mar 14 '21 at 07:32
  • If you don't have some pedagogical reason for writing the code yourself, you can do that simply at the CLI with **ImageMagick**, e.g. make a red image 640x480 and annotate with white text `magick -size 640x480 xc:red -fill white -annotate +10+20 "This is some text" result.png` – Mark Setchell Mar 14 '21 at 15:56
  • If you can push the boat out to C++, you could use **CImg** at http://cimg.eu – Mark Setchell Mar 14 '21 at 15:57

1 Answers1

5

For such a simple requirement you can use cairo, just adjust the png sizes and font:

#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;
}

Since you are on ubuntu:

sudo apt-get install -y libcairo2-dev

And compile with:

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

For more complex uses, you should combine cairo with pango:

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

David Ranieri
  • 39,972
  • 7
  • 52
  • 94