【问题标题】:Create transparent png of given text创建给定文本的透明png
【发布时间】:2013-09-10 16:11:21
【问题描述】:

我想创建一些给定文本的透明 png。我不想指定图像的宽度和高度,而是让它自动调整为文本大小。我已经尝试过 imagemagick 和 PHP,但是还没有完全掌握。我将如何使用这些技术或任何其他技术来做到这一点?另外,为什么一种技术比另一种更好?

imagemagick 解决方案

有效,但需要指定图像大小而不是自动调整为文本大小。

convert -size 560x85 xc:transparent -font Palatino-Bold -pointsize 72 -fill black -stroke red -draw "text 20,55 'Linux and Life'" linuxandlife.png

PHP 解决方案

除了在右侧切了一点外,其他作品都有效。此外,如果我用相同字体大小和字体类型的文本制作多个图像,并且它们都包含大写字母,那么图像的高度并不完全相同,但我希望它们是相同的。另外,今天第一次玩图像功能,如果我做错了什么请告诉我。

<?php

    $font_size = 11;
    $angle=0;
    //$fonttype="/usr/share/fonts/liberation/LiberationMono-Regular.ttf";
    $fonttype="/usr/share/fonts/dejavu/DejaVuSans.ttf";

    $text='Some text';
    $file='MyFile.png';

    $bbox = imagettfbbox($font_size, $angle, $fonttype, $text);
    $x1 = $bbox[2] - $bbox[0];
    $y1 = $bbox[1] - $bbox[7];

    $im = @imagecreatetruecolor($x1, $y1);
    imagesavealpha($im, true);
    imagealphablending($im, false);
    $color_background = imagecolorallocatealpha($im, 255, 255, 255, 127);
    imagefill($im, 0, 0, $color_background);
    $color_text = imagecolorallocate($im, 255, 0, 0);
    imagettftext($im, $font_size, $angle, 0, $font_size, $color_text, $fonttype, $text);
    imagepng($im,$file);
    imagedestroy($im);
?>

【问题讨论】:

  • 这对我来说看起来不错,在我的 PHP 测试中没有看到右侧的任何作物。
  • @waraker 你用什么来查看图片?
  • 脚本在根目录中创建:pic.imagecrisis.com/qysl4.png

标签: php linux imagemagick


【解决方案1】:

我会选择纯php解决方案,这样你就不用依赖像imagemagick这样的外部库了。

如果您使用浏览器缓存也许是个好主意,这样您就不必在每个请求时都生成图像。

只需在您的“imagettfbbox”之前添加以下代码,并将您的图像生成代码放在 ELSE 中。

$string = $text . filemtime($file);
$eTag = md5($string);
header("ETag: ".$eTag);
$httpModEtag  = !empty($_SERVER['HTTP_IF_NONE_MATCH'])? $_SERVER['HTTP_IF_NONE_MATCH']:"";
if($httpModEtag===$eTag)
{
  // tells the browser to use his cached image
  header("HTTP/1.1 304 Not Modified", true, 304);
}
else
{
  // tells the browser to refresh the cache
  header("Cache-Controll: must-revalidate");

  // ------ Place your Image Generation code here -------
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-29
    • 2011-08-31
    • 2013-03-26
    • 2013-06-20
    • 1970-01-01
    • 2012-11-02
    • 2023-04-01
    • 2016-10-13
    相关资源
    最近更新 更多