How to programmatically create and save an image with some text?

I would like to programmatically “compose” and save as PNG an image with a white background and a digit in the center, of a given font, colour, size.

Which approach may I have? I am thinking to plots, but it seems “exaggerated” for what I need…

Seems that Luxor does exactly this: A few examples · Luxor

I’ll give it a try …

1 Like

compose.jl can do it too: Forms · Compose.jltext

In Luxor I have problems to center the text string: How to center a text with Luxor

So I went back to Compose, but not speaking Lisp, it looks very scaring.
I have tried this, but the text doesn’t go on top of the rectangle:


using Colors, Compose
set_default_graphic_size(300px,300px)
img = compose(context(units=UnitBox(0,0,2,2)),
  compose(compose(context(), rectangle()), fill("white")),
  (context(), text(1, 1, "123", hcenter, vcenter), stroke("red"), fontsize(30pt)),
)

ok, got it with:

using Colors, Compose
set_default_graphic_size(300px,300px)
img = compose(context(units=UnitBox(0,0,2,2)),
  (context(), text(1, 1, "123", hcenter, vcenter), stroke("black"), fontsize(160pt)),
  compose(compose(context(), rectangle()), fill("white")),
)

Still I can’t change the font with Compose… font("Helvetica-Oblique") or font("CMU-Sans-Serif-Medium") seems not to have any effect.

Also, the exported PNG looks different than the preview in Juno.

EDIT: good about the last point… for some reasons the preview always display a serif font, but the PNG exported with img |> PNG("hello-world4.png") always draws with a sans-serif font that is what I want…

With GMT

using GMT

text(["Olá"], x=5, y=5, region=(0,10,0,10), font=(40,:red), justify=:CM, frame=(grid=5, fill=254), fmt=:png, show=true)

Replace frame=(grid=5, fill=254) by frame=(fill=254,) if you don’t want the frame and the grid. It was only to show the text positioning.

2 Likes