You are here

function image_imagick_annotate in Imagick 7

Annotates an image with text

Parameters

$image: An image object. The $image->resource value will be modified by this call.

$text: Text settings of the annotate effect.

$position: Position settings of the annotate effect.

Return value

TRUE or FALSE, based on success.

File

effects/imagick.annotate.inc, line 15

Code

function image_imagick_annotate(stdClass $image, $text, $position) {
  $padding = array(
    'x' => $position['padding_x'],
    'y' => $position['padding_y'],
  );

  // Check if percent is used
  $percent_x = explode('%', $padding['x']);
  if (count($percent_x) == 2) {
    $padding['x'] = $image->info['width'] / 100 * reset($percent_x);
  }
  $percent_y = explode('%', $padding['y']);
  if (count($percent_y) == 2) {
    $padding['y'] = $image->info['height'] / 100 * reset($percent_y);
  }

  // Create new transparent layer
  $text_layer = new Imagick();
  $text_layer
    ->newImage($image->info['width'] - 2 * $padding['x'], $image->info['height'] - 2 * $padding['y'], new ImagickPixel('transparent'));

  // Font properties
  $draw = new ImagickDraw();
  $draw
    ->setFont($text['font']);
  $draw
    ->setFillColor($text['HEX']);
  $draw
    ->setFontSize($text['size']);

  // Calculate text width and height
  $imagick = new Imagick();
  list($lines, $lineHeight) = _image_imagick_word_wrap_annotation($imagick, $draw, $text['text'], $text_layer
    ->getImageWidth());

  // Calcuate position
  $text_dimensions = $imagick
    ->queryFontMetrics($draw, $text['text']);
  $text_height = count($lines) * $lineHeight;
  list($left, $top) = explode('-', $position['anchor']);
  $y = image_filter_keyword($top, $text_layer
    ->getImageHeight(), $text_height);
  $y += $text_dimensions['textHeight'] + $text_dimensions['descender'];
  foreach ($lines as $line) {
    $line_dimensions = $imagick
      ->queryFontMetrics($draw, $line);
    $x = image_filter_keyword($left, $text_layer
      ->getImageWidth(), $line_dimensions['textWidth']);
    $text_layer
      ->annotateImage($draw, $x, $y, 0, $line);

    // Add lineheight for next line
    $y += $lineHeight;
  }
  return $image->resource
    ->compositeImage($text_layer, Imagick::COMPOSITE_OVER, $padding['x'], $padding['y']);
}