首页 > 解决方案 > 用 php-vips 覆盖文本

问题描述

我正在尝试使用 php-vips 库编写一个 PHP 函数来将文本覆盖到图像上。浏览文档,我找不到在此处的 libvips 文档中绘制文本的函数,此处php-vips 文档没有提供大量细节,似乎只是指导您使用 libvips 文档。我在一个 php-vips 问题 ( this ) 中找到了一个片段,但它使用了当前 php-vips 库中不存在的文本函数。有谁知道是否可以使用 php-vips 将文本绘制到图像上,如果可以,它是如何完成的?作为参考,我的用例是在通过 PDF 下载时在照片上绘制照片的时间戳。

标签: phpvips

解决方案


我给你做了一个演示程序:

#!/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]);

我可以这样运行它:

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

制作:

输出图像

text 方法的文档在这里:

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

不幸的是,phpdoc 标记不允许我们为选项生成文档。您需要在此处参考完整的 libvips 文档:

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


推荐阅读