Search code examples
luavips

vips - How to create justified text?


I'm using the vips library for manipulating some images, specifically its Lua binding, lua-vips, and I'm trying to create justified text images. I guess there is no available function in vips to do this directly, so I was wondering how to come up with an algorithm for that.

My first idea was to parse the text to be justified using a known algorithm for justification, but using image width of each separate word instead of number of characters to measure empty space. Then, for each of the lines, place the text images of each word next to each other, adding necessary space as black pixels between them.

However I couldn't figure out how to check line height, as it isn't necessarily equal to the text image height, so I'm not sure I'm using a good approach.


Solution

  • git master libvips supports justification now, and this feature should be in the upcoming libvips 8.8 (due spring 2019).

    Use it like this:

    $ vips text x.png "hello world sdkj hsdfkj herqkjh wehf" --width 100 --justify
    

    To make:

    sample justified output

    Or from Lua:

    x = vips.Image.text("hello world sdkj hsdfkj herqkjh wehf", {width = 100, justify = true})