1

I'm trying to write a PHP function to overlay text onto an image using the php-vips library. Looking through the documentation I can't find a function that draws text in the libvips documentation here and the php-vips documentation here doesn't provide a ton of detail and seems to just direct you to use the libvips documentation. I found a snippet in one of php-vips issues (this) but it uses a text function that doesn't exist in the current php-vips library. Does anyone know if it's possible to draw text onto an image with php-vips and if so how it is done? For reference my use case is to draw the timestamp for a photo over the photo when downloaded by PDF.

jcupitt
  • 10,213
  • 2
  • 23
  • 39
avorum
  • 2,243
  • 10
  • 39
  • 49
  • There's certainly a `text` method in current php-vips. Try the index in the libvips docs, or there's a handy vips function list here: https://libvips.github.io/libvips/API/current/func-list.html -- just search for "text". – jcupitt Mar 14 '19 at 20:53

1 Answers1

1

I made you a demo program:

#!/usr/bin/php 
<?php
require __DIR__ . '/vendor/autoload.php';
use Jcupitt\Vips;

$image = Vips\Image::newFromFile($argv[1], ['access' => 'sequential']);

// this renders the text to a one-band image ... set width to the pixels across
// of the area we want to render to to have it break lines for you
$text = Vips\Image::text('Hello world!', [
  'font' => 'sans 120', 
  'width' => $image->width - 100
]);
// make a constant image the size of $text, but with every pixel red ... tag it
// as srgb
$red = $text->newFromImage([255, 0, 0])->copy(['interpretation' => 'srgb']);
// use the text mask as the alpha for the constant red image
$overlay = $red->bandjoin($text);

// composite the text on the image
$out = $image->composite($overlay, "over", ['x' => 100, 'y' => 100]);

$out->writeToFile($argv[2]);

I can run it like this:

$ ./render_text.php ~/pics/tiny_marble.jpg x.jpg

To Make:

output image

The docs for the text method are here:

https://libvips.github.io/php-vips/docs/classes/Jcupitt.Vips.ImageAutodoc.html#method_text

Unfortunately phpdoc markup doesn't let us generate docs for the options. You need to refer to the full libvips docs here:

https://libvips.github.io/libvips/API/current/libvips-create.html#vips-text

jcupitt
  • 10,213
  • 2
  • 23
  • 39
  • In the text documentation it notes that there's an options parameter, is there any reference of what those options are? – avorum Mar 18 '19 at 13:25
  • Yes, those are the options listed for `vips_text()`: https://libvips.github.io/libvips/API/current/libvips-create.html#vips-text `font`, `align`, `dpi`, etc. You can get a summary at the command-line too, try entering "vips text". – jcupitt Mar 18 '19 at 13:54