【问题标题】:How can I change the color of a specific word using Imagick in PHP?如何在 PHP 中使用 Imagick 更改特定单词的颜色?
【发布时间】:2016-01-22 03:04:27
【问题描述】:

我目前正在使用annotateImage 向图像添加一些文本。

/* Black text */
$draw->setFillColor('black');

/* Font properties */
$draw->setFont('Bookman-DemiItalic');
$draw->setFontSize( 30 );

$image->annotateImage($draw, 10, 45, 0, 'The fox jumped over the lazy dog');

这当前以黑色显示所有文本。我正在寻找一种方法来将单词 fox 的颜色更改为 red,但我没有想法。

我怎样才能做到这一点?

【问题讨论】:

标签: php text colors imagick


【解决方案1】:

正如 Danack 的评论所建议的,如果有人需要,这是我的解决方案。 parseText 函数查找具有color, font, size 属性的<span> 标签并返回一个数组。

The <span color="red">fox</span> jumped over the lazy <span color="green">dog</span>.

在上面的文本中,单词 fox 将具有 color=red 属性,而 dog 将具有 color=green

使用数组,我们可以绘制常规文本,跟踪定位,也可以绘制风格化文本。

function parseText($txt) {
  if ( strstr($txt, '<span') ) {
    $txt = preg_split('@(<span(?:\\\?.)*?>(?:\\\?.)*?</span>)@', $txt, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
    $arr = array();
    foreach ( $txt as $t ) {
      if ( strstr($t, '<span') ) {
        $tag = array();
        preg_match('@<span\s*((?:\\\?.)*?)\s*>((?:\\\?.)*?)</span>@', $t, $m);
        $attrs = $m[1];
        $inner = $m[2];
        if ( $attrs ) {
          $attrs = preg_split('@((?:\\\?.)*?=["\'](?:\\\?.)*?["\'])\s*@', $attrs, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
          foreach ( $attrs as $a ) {
            $a = explode('=', $a);
            $tag[ $a[0] ] = trim($a[1], '"\'');
          }
        }
        $tag['text'] = $inner;
        $arr[] = $tag;
      } else {
        $arr[] = array( 'text' => $t );
      }
      $txt = $arr;
    }
  }
  return $txt;
}

function newStyle($image, $draw, $t, &$width) {
  if ( $t['color'] )  $draw->setFillColor($t['color']);
  if ( $t['size']  )  $draw->setFontSize($t['size']);
  if ( $t['font']  )  $draw->setFont($t['font']);
  $metrics = $image->queryFontMetrics($draw, $t['text'], FALSE);
  $width = $metrics['textWidth'];
}

// To use it

function defaultStyle($draw) {
  $draw->setFillColor('black');
  $draw->setFont('Bookman-DemiItalic');
  $draw->setFontSize(20);
}

defaultStyle($draw);

$txt = 'The <span color="red">fox</span> jumped over the lazy <span color="green">dog</span>.';
$x = 45;
$y = 45;
$txt = parseText($txt);
if ( is_array($txt) ) {
  foreach ( $txt as $t ) {
    defaultStyle($draw);
    newStyle($image, $draw, $t, $width);
    $image->annotateImage($draw, $x, $y, 0, $t['text']);
    $x += $width;
  }
} else {
  $image->annotateImage($draw, $x, $y, 0, $txt);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-02
    • 1970-01-01
    • 1970-01-01
    • 2018-03-01
    • 1970-01-01
    • 2013-06-20
    • 2021-12-01
    相关资源
    最近更新 更多