function createEmailPic($jid, $email) { $cachefile = DOCUMENT_ROOT . '/cache/' . $jid . '_email.png'; if (file_exists(DOCUMENT_ROOT . '/cache/' . $jid . '_email.png')) { unlink(DOCUMENT_ROOT . '/cache/' . $jid . '_email.png'); } $draw = new ImagickDraw(); $draw->setFontSize(13); $draw->setGravity(Imagick::GRAVITY_CENTER); $canvas = new Imagick(); $metrics = $canvas->queryFontMetrics($draw, $email); $canvas->newImage($metrics['textWidth'], $metrics['textHeight'], "transparent", "png"); $canvas->annotateImage($draw, 0, 0, 0, $email); $canvas->setImageFormat('PNG'); $canvas->writeImage($cachefile); }
function wordWrapAnnotation(\Imagick $imagick, $draw, $text, $maxWidth) { $words = explode(" ", $text); $lines = array(); $i = 0; $lineHeight = 0; while ($i < count($words)) { $currentLine = $words[$i]; if ($i + 1 >= count($words)) { $lines[] = $currentLine; break; } //Check to see if we can add another word to this line $metrics = $imagick->queryFontMetrics($draw, $currentLine . ' ' . $words[$i + 1]); while ($metrics['textWidth'] <= $maxWidth) { //If so, do it and keep doing it! $currentLine .= ' ' . $words[++$i]; if ($i + 1 >= count($words)) { break; } $metrics = $imagick->queryFontMetrics($draw, $currentLine . ' ' . $words[$i + 1]); } //We can't add the next word to this line, so loop to the next line $lines[] = $currentLine; $i++; //Finally, update line height if ($metrics['textHeight'] > $lineHeight) { $lineHeight = $metrics['textHeight']; } } return array($lines, $lineHeight); }
/** * (non-PHPdoc) * @see Imagine\Image\FontInterface::box() */ public function box($string, $angle = 0) { $text = new \ImagickDraw(); $text->setFont($this->file); $text->setFontSize($this->size); $info = $this->imagick->queryFontMetrics($text, $string); $box = new Box($info['textWidth'], $info['textHeight']); return $box; }
/** * (non-PHPdoc) * @see Imagine\Draw\DrawerInterface::text() */ public function text($string, AbstractFont $font, PointInterface $position, $angle = 0) { try { $pixel = $this->getColor($font->getColor()); $text = new \ImagickDraw(); $text->setFont($font->getFile()); $text->setFontSize($font->getSize()); $text->setFillColor($pixel); $text->setTextAntialias(true); $info = $this->imagick->queryFontMetrics($text, $string); $rad = deg2rad($angle); $cos = cos($rad); $sin = sin($rad); $x1 = round(0 * $cos - 0 * $sin); $x2 = round($info['textWidth'] * $cos - $info['textHeight'] * $sin); $y1 = round(0 * $sin + 0 * $cos); $y2 = round($info['textWidth'] * $sin + $info['textHeight'] * $cos); $xdiff = 0 - min($x1, $x2); $ydiff = 0 - min($y1, $y2); $this->imagick->annotateImage($text, $position->getX() + $x1 + $xdiff, $position->getY() + $y2 + $ydiff, $angle, $string); $pixel->clear(); $pixel->destroy(); $text->clear(); $text->destroy(); } catch (\ImagickException $e) { throw new RuntimeException('Draw text operation failed', $e->getCode(), $e); } }
/** * Calculates size for bounding box of string written in given font. * * @param string $string * @param FontInterface $font * * @return bool|Box Instance of Box object, false on error */ public static function calculateTextSize($string, FontInterface $font) { $imagine = Tygh::$app['image']; if ($imagine instanceof \Imagine\Imagick\Imagine && class_exists('ImagickDraw')) { $text = new \ImagickDraw(); $text->setFont($font->getFile()); if (version_compare(phpversion("imagick"), "3.0.2", ">=")) { $text->setResolution(96, 96); $text->setFontSize($font->getSize()); } else { $text->setFontSize((int) ($font->getSize() * (96 / 72))); } $imagick = new \Imagick(); $info = $imagick->queryFontMetrics($text, $string); $text->clear(); $text->destroy(); $imagick->clear(); $imagick->destroy(); return new Box($info['textWidth'], $info['textHeight']); } if ($imagine instanceof \Imagine\Gd\Imagine && function_exists('imagettfbbox')) { $ttfbbox = imagettfbbox($font->getSize(), 0, $font->getFile(), $string); return new Box(abs($ttfbbox[2]), abs($ttfbbox[7])); } return false; }
function writeText($text) { if ($this->printer == null) { throw new LogicException("Not attached to a printer."); } if ($text == null) { return; } $text = trim($text, "\n"); /* Create Imagick objects */ $image = new \Imagick(); $draw = new \ImagickDraw(); $color = new \ImagickPixel('#000000'); $background = new \ImagickPixel('white'); /* Create annotation */ //$draw -> setFont('Arial');// (not necessary?) $draw->setFontSize(24); // Size 21 looks good for FONT B $draw->setFillColor($color); $draw->setStrokeAntialias(true); $draw->setTextAntialias(true); $metrics = $image->queryFontMetrics($draw, $text); $draw->annotation(0, $metrics['ascender'], $text); /* Create image & draw annotation on it */ $image->newImage($metrics['textWidth'], $metrics['textHeight'], $background); $image->setImageFormat('png'); $image->drawImage($draw); //$image -> writeImage("test.png"); /* Save image */ $escposImage = new EscposImage(); $escposImage->readImageFromImagick($image); $size = Printer::IMG_DEFAULT; $this->printer->bitImage($escposImage, $size); }
public function makeImageOfCertification() { date_default_timezone_set('UTC'); $timeStamp = date('jS F Y'); $text = "CERTIFIED COPY" . "\n" . $this->serial . "\n" . $timeStamp; $image = new \Imagick(); $draw = new \ImagickDraw(); $color = new \ImagickPixel('#000000'); $background = new \ImagickPixel("rgb(85, 196, 241)"); $draw->setFont($this->container->getParameter('assetic.write_to') . $this->container->get('templating.helper.assets')->getUrl('fonts/futura.ttf')); $draw->setFontSize(24); $draw->setFillColor($color); $draw->setTextAntialias(true); $draw->setStrokeAntialias(true); //Align text to the center of the background $draw->setTextAlignment(\Imagick::ALIGN_CENTER); //Get information of annotation image $metrics = $image->queryFontMetrics($draw, $text); //Calc the distance(pixels) to move the sentences $move = $metrics['textWidth'] / 2; $draw->annotation($move, $metrics['ascender'], $text); //Create an image of certification $image->newImage($metrics['textWidth'], $metrics['textHeight'], $background); $image->setImageFormat('png'); $image->drawImage($draw); //Save an image temporary $image->writeImage("cert_" . $this->serial . "_.png"); }
public function text_metrics($text, $size, $font_file) { $draw = new $this->draw_class(); $draw->setFont($font_file); $draw->setFontSize($size); $metrics = $this->image->queryFontMetrics($draw, $text, true); return array('ascender' => floor($metrics['boundingBox']['y2']), 'descender' => floor(-$metrics['boundingBox']['y1']), 'width' => floor($metrics['textWidth']), 'height' => floor($metrics['boundingBox']['y2'] - $metrics['boundingBox']['y1'])); }
/** * @see \wcf\system\image\adapter\IImageAdapter::textFitsImage() */ public function textFitsImage($text, $margin, $font, $size) { $draw = new \ImagickDraw(); $draw->setFont($font); $draw->setFontSize($size); $metrics = $this->imagick->queryFontMetrics($draw, $text); return $metrics['textWidth'] + 2 * $margin <= $this->getWidth() && $metrics['textHeight'] + 2 * $margin <= $this->getHeight(); }
public function textBoundingBox($size, $font, $text) { $im = new Imagick(); $draw = new ImagickDraw(); $draw->setFontSize($size * $this->fontSizeScale); $draw->setFont($font); $fontMetrics = $im->queryFontMetrics($draw, $text); return array($fontMetrics['textWidth'], $fontMetrics['textHeight'] * $this->lineHeightScale, $fontMetrics['ascender'] * $this->lineHeightScale); }
/** * {@inheritdoc} */ public function box($string, $angle = 0) { $text = new \ImagickDraw(); $text->setFont($this->file); /** * @see http://www.php.net/manual/en/imagick.queryfontmetrics.php#101027 * * ensure font resolution is the same as GD's hard-coded 96 */ if (version_compare(phpversion("imagick"), "3.0.2", ">=")) { $text->setResolution(96, 96); $text->setFontSize($this->size); } else { $text->setFontSize((int) ($this->size * (96 / 72))); } $info = $this->imagick->queryFontMetrics($text, $string); $box = new Box($info['textWidth'], $info['textHeight']); return $box; }
function render() { $text = "Lorem ipsum"; $im = new \Imagick(); $draw = new \ImagickDraw(); $draw->setStrokeColor("none"); $draw->setFont("../fonts/Arial.ttf"); $draw->setFontSize(96); $draw->setTextAlignment(\Imagick::ALIGN_LEFT); $metrics = $im->queryFontMetrics($draw, $text); return print_table($metrics); }
/** * Generates and dies with an image containing the heading and the text of the error. * * @param string $headingText The heading of the error. * @param string $errorText The text of the error. */ public function generate($headingText, $errorText) { $draw = new ImagickDraw(); $draw->setFillColor('#777777'); $draw->setFontSize(15); $draw->setFont('fonts/exo2bold.ttf'); $headingMetrics = $this->canvas->queryFontMetrics($draw, $headingText); $draw->setFont('fonts/exo2regular.ttf'); $textMetrics = $this->canvas->queryFontMetrics($draw, $errorText); $this->canvas->newImage(max($textMetrics['textWidth'], $headingMetrics['textWidth']) + 6, $textMetrics['textHeight'] + $headingMetrics['textHeight'] + 6, new ImagickPixel('white')); $this->canvas->annotateImage($draw, 3, $headingMetrics['textHeight'] * 2, 0, $errorText); $draw->setFont('fonts/exo2bold.ttf'); $draw->setFillColor('#333333'); $draw->setGravity(Imagick::GRAVITY_NORTH); $this->canvas->annotateImage($draw, 3, 3, 0, $headingText); $this->canvas->setImageFormat('png'); header('Content-Type: image/' . $this->canvas->getImageFormat()); header("Cache-Control: max-age=60"); header("Expires: " . gmdate("D, d M Y H:i:s", time() + 60) . " GMT"); die($this->canvas); }
/** * Internal * * Fits a string into box with given width */ private function wrapText($string, $text, $angle, $width) { $result = ''; $words = explode(' ', $string); foreach ($words as $word) { $teststring = $result . ' ' . $word; $testbox = $this->imagick->queryFontMetrics($text, $teststring, true); if ($testbox['textWidth'] > $width) { $result .= ($result == '' ? '' : "\n") . $word; } else { $result .= ($result == '' ? '' : ' ') . $word; } } return $result; }
/** * Generate and save the image with a copyright text at the bottom right corner * * @param string $text The copyright text * @param int $fontSize OPTIONAL the copyright font size DEFAULT 22 * @param string $font OPTIONAL the copyright font DEFAULT "Verdana" * @param string $position OPTIONAL the position to put copyright text DEFAULT "bottom-right" Possibles * Values ("bottom-right", "bottom-left", "top-right", "top-left") */ public function copyrightImage(string $text, int $fontSize = 22, string $font = 'Verdana', string $position = 'bottom-right') { $draw = new \ImagickDraw(); $draw->setFontSize($fontSize); $draw->setFont($font); $draw->setFillColor('#ffffff'); $draw->setTextUnderColor('#00000088'); $textMetrics = $this->image->queryFontMetrics($draw, $text); $textWidth = $textMetrics['textWidth'] + 2 * $textMetrics['boundingBox']['x1']; $extraTextHeight = $textMetrics['descender']; $textHeight = $textMetrics['textHeight'] + $extraTextHeight; switch ($position) { case 'bottom-right': $width = $this->image->getImageWidth() - $textWidth; $height = $this->image->getImageHeight() + $extraTextHeight; $width -= static::$EXTRA_TEXT_PADDING; $height -= static::$EXTRA_TEXT_PADDING; break; case 'bottom-left': $width = 0; $height = $this->image->getImageHeight() + $extraTextHeight; $width += static::$EXTRA_TEXT_PADDING; $height -= static::$EXTRA_TEXT_PADDING; break; case 'top-right': $width = $this->image->getImageWidth() - $textWidth; $height = $textHeight; $width -= static::$EXTRA_TEXT_PADDING; $height += static::$EXTRA_TEXT_PADDING; break; case 'top-left': $width = 0; $height = $textHeight; $width += static::$EXTRA_TEXT_PADDING; $height += static::$EXTRA_TEXT_PADDING; break; default: $width = $this->image->getImageWidth() - $textWidth; $height = $this->image->getImageHeight() + $extraTextHeight; $width -= static::$EXTRA_TEXT_PADDING; $height -= static::$EXTRA_TEXT_PADDING; break; } $this->image->annotateImage($draw, $width, $height, 0, $text); $this->image->writeImage($this->imageSavePath . DIRECTORY_SEPARATOR . $this->imageName . '_copyright' . '.' . $this->imageExtension); }
/** * @param array $options * 'watermark' => waImage|string $watermark * 'opacity' => float|int 0..1 * 'align' => self::ALIGN_* const * 'font_file' => null|string If null - will be used some default font. Note: use when watermark option is text * 'font_size' => float Size of font. Note: use when watermark option is text * 'font_color' => string Hex-formatted of color (without #). Note: use when watermark option is text * 'text_orientation' => self::ORIENTATION_* const. Note: use when watermark option is text * @return mixed */ protected function _watermark($options) { // export options to php-vars foreach ($options as $name => $value) { ${$name} = $value; } $opacity = min(max($opacity, 0), 1); /** * @var waImage $watermark */ if ($watermark instanceof waImage) { $offset = $this->calcWatermarkOffset($watermark->width, $watermark->height, $align); $watermark = new Imagick($watermark->file); $watermark->evaluateImage(Imagick::EVALUATE_MULTIPLY, $opacity, Imagick::CHANNEL_ALPHA); $this->im->compositeImage($watermark, Imagick::COMPOSITE_DEFAULT, $offset[0], $offset[1]); $watermark->clear(); $watermark->destroy(); } else { $text = (string) $watermark; if (!$text) { return; } $font_size = 24 * $font_size / 18; // 24px = 18pt $font_color = new ImagickPixel('#' . $font_color); $watermark = new ImagickDraw(); $watermark->setFillColor($font_color); $watermark->setFillOpacity($opacity); if ($font_file && file_exists($font_file)) { $watermark->setFont($font_file); } $watermark->setFontSize($font_size); // Throws ImagickException on error $metrics = $this->im->queryFontMetrics($watermark, $text); $width = $metrics['textWidth']; $height = $metrics['textHeight']; if ($text_orientation == self::ORIENTATION_VERTICAL) { list($width, $height) = array($height, $width); } $offset = $this->calcWatermarkTextOffset($width, $height, $align, $text_orientation); $this->im->annotateImage($watermark, $offset[0], $offset[1], $text_orientation == self::ORIENTATION_VERTICAL ? -90 : 0, $text); $watermark->clear(); $watermark->destroy(); } }
function a0nCRQ($msg, $padx, $pady, $bc, $fc, $tc) { $im = new Imagick(); $idraw = new ImagickDraw(); $idraw->setFontSize(30); $idraw->setFont('MyriadPro-Regular.otf'); $idraw->setGravity(Imagick::GRAVITY_CENTER); $metrics = $im->queryFontMetrics($idraw, $msg); $im->newPseudoImage($metrics["textWidth"] + $padx * 2, $metrics["textHeight"] + $pady * 2, "xc:none"); $idraw->setFillColor($fc); $idraw->setStrokeColor($bc); $idraw->roundrectangle(0, 0, $metrics["textWidth"] + $padx * 2 - 1, $metrics["textHeight"] + $pady * 2 - 1, 10, 10); $idraw->setFillColor($tc); $idraw->setStrokeColor($tc); $idraw->annotation(0, 0, $msg); $im->drawImage($idraw); return $im; }
function fl_text_render($_file, $id, $text, $fontname, $fontsize, $color = "#000000", $out_image_file_type = "png") { $font = locate_font($fontname); if ($font === false) { fllog('fl_text_render: font `' . $fontname . '` not found at `' . flvault . $fontname . '`'); return false; } $render = false; $out_image_file_type = strtolower($out_image_file_type); $cachefile = flcache . $id . '.' . $out_image_file_type; if ($_file !== false) { if (file1_is_older($cachefile, $_file)) { $render = true; } } else { $render = true; } if ($render === true) { try { $draw = new ImagickDraw(); $draw->setFont($font); $draw->setFontSize(intval($fontsize)); $draw->setGravity(Imagick::GRAVITY_CENTER); $draw->setFillColor($color); $canvas = new Imagick(); $m = $canvas->queryFontMetrics($draw, htmlspecialchars_decode($text)); $canvas->newImage($m['textWidth'], $m['textHeight'], "transparent", $out_image_file_type); $canvas->annotateImage($draw, 0, 0, 0, $text); $canvas->setImageFormat(strtoupper($out_image_file_type)); $canvas->writeImage($cachefile); fllog('Writing to: ' . $cachefile); $canvas->clear(); $canvas->destroy(); $draw->clear(); $draw->destroy(); } catch (Exception $e) { fllog('fl_text_render() Error: ', $e->getMessage()); return false; } } return $cachefile; }
/** * {@inheritdoc} */ public function text($string, AbstractFont $font, PointInterface $position, $angle = 0) { try { $pixel = $this->getColor($font->getColor()); $text = new \ImagickDraw(); $text->setFont($font->getFile()); /** * @see http://www.php.net/manual/en/imagick.queryfontmetrics.php#101027 * * ensure font resolution is the same as GD's hard-coded 96 */ if (version_compare(phpversion("imagick"), "3.0.2", ">=")) { $text->setResolution(96, 96); $text->setFontSize($font->getSize()); } else { $text->setFontSize((int) ($font->getSize() * (96 / 72))); } $text->setFillColor($pixel); $text->setTextAntialias(true); $info = $this->imagick->queryFontMetrics($text, $string); $rad = deg2rad($angle); $cos = cos($rad); $sin = sin($rad); // round(0 * $cos - 0 * $sin) $x1 = 0; $x2 = round($info['characterWidth'] * $cos - $info['characterHeight'] * $sin); // round(0 * $sin + 0 * $cos) $y1 = 0; $y2 = round($info['characterWidth'] * $sin + $info['characterHeight'] * $cos); $xdiff = 0 - min($x1, $x2); $ydiff = 0 - min($y1, $y2); $this->imagick->annotateImage($text, $position->getX() + $x1 + $xdiff, $position->getY() + $y2 + $ydiff, $angle, $string); $pixel->clear(); $pixel->destroy(); $text->clear(); $text->destroy(); } catch (\ImagickException $e) { throw new RuntimeException('Draw text operation failed', $e->getCode(), $e); } return $this; }
protected function _generateImage($text, $filePath) { $image = new Imagick(); $draw = new ImagickDraw(); $draw->setFont('lib/SwiftOtter/OpenSans-Regular.ttf'); $draw->setFontSize('13'); $metrics = $image->queryFontMetrics($draw, $text, false); $width = 100; $padding = 10; if (isset($metrics['textWidth'])) { $width = $metrics['textWidth'] + $padding * 2; } $image->newImage($width, 17, new ImagickPixel('#f98b25')); $draw->setFillColor('#ffffff'); $image->annotateImage($draw, $padding / 2 + 3, $padding + 3, 0, $text); $draw->setFillColor('#a04300'); $image->borderImage('#a04300', 1, 1); $image->setFormat('gif'); $image->writeImage($filePath); return $image; }
public function writeText($text) { if ($this->printer == null) { throw new LogicException("Not attached to a printer."); } if ($text == null) { return; } $text = trim($text, "\n"); /* Create Imagick objects */ $image = new \Imagick(); $draw = new \ImagickDraw(); $color = new \ImagickPixel('#000000'); $background = new \ImagickPixel('white'); /* Create annotation */ if ($this->font !== null) { // Allow fallback on defaults as necessary $draw->setFont($this->font); } /* In Arial, size 21 looks good as a substitute for FONT_B, 24 for FONT_A */ $draw->setFontSize($this->fontSize); $draw->setFillColor($color); $draw->setStrokeAntialias(true); $draw->setTextAntialias(true); $metrics = $image->queryFontMetrics($draw, $text); $draw->annotation(0, $metrics['ascender'], $text); /* Create image & draw annotation on it */ $image->newImage($metrics['textWidth'], $metrics['textHeight'], $background); $image->setImageFormat('png'); $image->drawImage($draw); // debugging if you want to view the images yourself //$image -> writeImage("test.png"); /* Save image */ $escposImage = new ImagickEscposImage(); $escposImage->readImageFromImagick($image); $size = Printer::IMG_DEFAULT; $this->printer->bitImage($escposImage, $size); }
public function text($text, $fontFile, $size = 12, $color = '#000000', $corner = self::CORNER_LEFT_TOP, $offsetX = 0, $offsetY = 0, $angle = 0) { $this->checkLoaded(); /* This object will hold the font properties */ $draw = new \ImagickDraw(); /* Setting gravity to the center changes the origo where annotation coordinates are relative to */ $draw->setGravity(\Imagick::GRAVITY_CENTER); /* Use a custom truetype font */ $draw->setFont($fontFile); /* Set the font size */ $draw->setFontSize($size); $im = new \Imagick(); /* Get the text properties */ $properties = $im->queryFontMetrics($draw, $text); /* Region size for the watermark. Add some extra space on the sides */ $textWidth = intval($properties['textWidth'] + 5); $textHeight = intval($properties['textHeight'] + 5); /* Create a canvas using the font properties. Add some extra space on width and height */ $im->newImage($textWidth, $textHeight, new \ImagickPixel("transparent")); /* Use png format */ $draw->setFillColor($color); $im->setImageFormat('png'); $im->annotateImage($draw, 0, 0, 0, $text); list($posX, $posY) = $this->getCornerPosition($corner, $textWidth, $textHeight, $offsetX, $offsetY); /* Composite the watermark on the image to the top left corner */ $this->_image->compositeImage($im, \Imagick::COMPOSITE_OVER, $posX, $posY); return $this; }
/** * Renders the CAPTCHA image based on the code using ImageMagick library. * @param string $code the verification code * @since 1.1.13 */ protected function renderImageImagick($code) { $backColor = $this->transparent ? new ImagickPixel('transparent') : new ImagickPixel(sprintf('#%06x', $this->backColor)); $foreColor = new ImagickPixel(sprintf('#%06x', $this->foreColor)); $image = new Imagick(); $image->newImage($this->width, $this->height, $backColor); if ($this->fontFile === null) { $this->fontFile = dirname(__FILE__) . '/SpicyRice.ttf'; } $draw = new ImagickDraw(); $draw->setFont($this->fontFile); $draw->setFontSize(30); $fontMetrics = $image->queryFontMetrics($draw, $code); $length = strlen($code); $w = (int) $fontMetrics['textWidth'] - 8 + $this->offset * ($length - 1); $h = (int) $fontMetrics['textHeight'] - 8; $scale = min(($this->width - $this->padding * 2) / $w, ($this->height - $this->padding * 2) / $h); $x = 10; $y = round($this->height * 27 / 40); for ($i = 0; $i < $length; ++$i) { $draw = new ImagickDraw(); $draw->setFont($this->fontFile); $draw->setFontSize((int) (rand(26, 32) * $scale * 0.8)); $draw->setFillColor($foreColor); $image->annotateImage($draw, $x, $y, rand(-10, 10), $code[$i]); $fontMetrics = $image->queryFontMetrics($draw, $code[$i]); $x += (int) $fontMetrics['textWidth'] + $this->offset; } header('Pragma: public'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Content-Transfer-Encoding: binary'); header("Content-Type: image/png"); $image->setImageFormat('png'); echo $image; }
flush(); $image = new Imagick(); $draw = new ImagickDraw(); $color = new ImagickPixel('black'); $background = new ImagickPixel('white'); // Set Font properties //$draw->setFont('Arial'); $draw->setFont($fontname); $draw->setFontSize($fontsize); $draw->setFillColor($color); $draw->setStrokeAntialias(true); $draw->setTextAntialias(true); echo '<li>bestimme Dimension des Textes</li>'; flush(); // Get font metrics $metrics = $image->queryFontMetrics($draw, $text); // draw the text $topborder = 2; $spaceatend = 5; echo '<li>generiere Text</li>'; flush(); $draw->annotation(0, $topborder + $metrics['ascender'], $text); // create image of correct size echo '<li>generiere Bild</li>'; flush(); $image->newImage($spaceatend + $metrics['textWidth'], $topborder + $metrics['textHeight'], $background); $image->setImageFormat('png'); echo '<li>zeichne Text ins Bild</li>'; flush(); $image->drawImage($draw); // save to queue dir
public function watermarkText($overlayText, $position, $param = array('rotation' => 0, 'opacity' => 50, 'color' => 'FFF', 'size' => null)) { $imagick = new Imagick(); $imagick->readImage($this->_file); $size = null; if ($param['size']) { $size = $param['size']; } else { $text = new ImagickDraw(); $text->setFontSize(12); $text->setFont($this->_watermarkFont); $im = new Imagick(); $stringBox12 = $im->queryFontMetrics($text, $overlayText, false); $string12 = $stringBox12['textWidth']; $size = (int) ($this->_width / 2) * 12 / $string12; $im->clear(); $im->destroy(); $text->clear(); $text->destroy(); } $draw = new ImagickDraw(); $draw->setFont($this->_watermarkFont); $draw->setFontSize($size); $draw->setFillOpacity($param['opacity']); switch ($position) { case Gio_Image_Abstract::POS_TOP_LEFT: $draw->setGravity(Imagick::GRAVITY_NORTHWEST); break; case Gio_Image_Abstract::POS_TOP_RIGHT: $draw->setGravity(Imagick::GRAVITY_NORTHEAST); break; case Gio_Image_Abstract::POS_MIDDLE_CENTER: $draw->setGravity(Imagick::GRAVITY_CENTER); break; case Gio_Image_Abstract::POS_BOTTOM_LEFT: $draw->setGravity(Imagick::GRAVITY_SOUTHWEST); break; case Gio_Image_Abstract::POS_BOTTOM_RIGHT: $draw->setGravity(Imagick::GRAVITY_SOUTHEAST); break; default: throw new Exception('Do not support ' . $position . ' type of alignment'); break; } $draw->setFillColor('#' . $param['color']); $imagick->annotateImage($draw, 5, 5, $param['rotation'], $overlayText); $imagick->writeImage($this->_file); $imagick->clear(); $imagick->destroy(); $draw->clear(); $draw->destroy(); }
/** * Returns the font height in pixels * * @param ImagickDraw $font * @return int */ function zp_imageFontHeight($font) { $temp = new Imagick(); $metrics = $temp->queryFontMetrics($font, "The quick brown fox jumps over the lazy dog"); $temp->destroy(); return $metrics['characterHeight']; }
public function addWatermark($inputImage, $fileType = null, $viewingUser = null, $isRebuild = false) { $this->standardizeViewingUserReference($viewingUser); $fileType = $this->getImageFileType($inputImage, $fileType); if ($fileType === null) { return false; } $xenOptions = XenForo_Application::getOptions(); if (empty($xenOptions->sonnbXG_watermark['enabled'])) { return false; } $isImagick = $xenOptions->imageLibrary['class'] === 'imPecl'; $watermarkOptions = $this->getWatermarkSettings($isRebuild); try { switch ($watermarkOptions['overlay']) { case 'image': $watermarkFile = tempnam(XenForo_Helper_File::getTempDir(), 'xf'); if (Zend_Uri::check($watermarkOptions['url'])) { $client = XenForo_Helper_Http::getClient($watermarkOptions['url']); $response = $client->request('GET'); if ($response->isSuccessful()) { @file_put_contents($watermarkFile, $response->getBody()); } else { return false; } } elseif (is_file($watermarkOptions['url'])) { $this->copyFile($watermarkOptions['url'], $watermarkFile); } else { return false; } if (!($watermarkFileInfo = @getimagesize($watermarkFile))) { return false; } if ($isImagick) { $srcResource = new Imagick($inputImage); $wtmResource = new Imagick($watermarkFile); } else { $srcResource = $this->createImageFromFile($inputImage, $fileType); //TODO: Check watermark image size against input image. $wtmResource = $this->createImageFromFile($watermarkFile, $watermarkFileInfo[2]); } $this->addWatermarkBySource($srcResource, $wtmResource, $watermarkOptions['position'], $watermarkOptions['margin'], $inputImage, $fileType); @unlink($watermarkFile); break; case 'text': default: $findArray = array('{username}', '{user_id}', '{email}'); $replaceArray = array($viewingUser['username'], $viewingUser['user_id'], $viewingUser['email']); $watermarkOptions['text'] = str_replace($findArray, $replaceArray, $watermarkOptions['text']); if (empty($watermarkOptions['text'])) { return false; } if ($isImagick) { $wtmResource = new Imagick(); $draw = new ImagickDraw(); $color = new ImagickPixel($watermarkOptions['textColor']); $background = new ImagickPixel('none'); $draw->setFontSize($watermarkOptions['textSize']); $draw->setFillColor($color); $draw->setStrokeAntialias(true); $draw->setTextAntialias(true); $metrics = $wtmResource->queryFontMetrics($draw, $watermarkOptions['text']); $draw->annotation(0, $metrics['ascender'], $watermarkOptions['text']); $wtmResource->newImage($metrics['textWidth'], $metrics['textHeight'], $background); $wtmResource->setImageFormat('png'); $wtmResource->drawImage($draw); $srcResource = new Imagick($inputImage); } else { $padding = 10; $font = 'styles/sonnb/XenGallery/watermark.ttf'; if (!empty($watermarkOptions['font']) && is_file($watermarkOptions['font'])) { $font = $watermarkOptions['font']; } if (function_exists('imagettfbbox')) { $textDimension = imagettfbbox($watermarkOptions['textSize'], 0, $font, $watermarkOptions['text']); $width = abs($textDimension[4] - $textDimension[0]) + $padding; $height = abs($textDimension[5] - $textDimension[1]) + $padding; } else { $width = ImageFontWidth($watermarkOptions['textSize']) * strlen($watermarkOptions['text']); $height = ImageFontHeight($watermarkOptions['textSize']); } $wtmResource = @imagecreatetruecolor($width, $height); if (strtolower($watermarkOptions['bgColor']) === 'transparent') { imagesavealpha($wtmResource, true); $bgColor = imagecolorallocatealpha($wtmResource, 0, 0, 0, 127); imagefill($wtmResource, 0, 0, $bgColor); } else { $bgColorRbg = $this->hex2rgb($watermarkOptions['bgColor']); $bgColor = imagecolorallocate($wtmResource, $bgColorRbg['red'], $bgColorRbg['green'], $bgColorRbg['blue']); imagefill($wtmResource, 0, 0, $bgColor); } $txtColorRbg = $this->hex2rgb($watermarkOptions['textColor']); $txtColor = imagecolorallocate($wtmResource, $txtColorRbg['red'], $txtColorRbg['green'], $txtColorRbg['blue']); imagettftext($wtmResource, $watermarkOptions['textSize'], 0, $padding / 2, $height - $padding / 2, $txtColor, $font, $watermarkOptions['text']); $srcResource = $this->createImageFromFile($inputImage, $fileType); } $this->addWatermarkBySource($srcResource, $wtmResource, $watermarkOptions['position'], $watermarkOptions['margin'], $inputImage, $fileType); break; } } catch (Exception $e) { XenForo_Error::logException($e); return false; } }
/** * 图像添加文字 * @param string $text 添加的文字 * @param string $font 字体路径 * @param integer $size 字号 * @param string $color 文字颜色 * @param integer $locate 文字写入位置 * @param integer $offset 文字相对当前位置的偏移量 * @param integer $angle 文字倾斜角度 * @throws \Exception */ public function text($text, $font, $size, $color = '#00000000', $locate = Image::IMAGE_WATER_SOUTHEAST, $offset = 0, $angle = 0) { //资源检测 if (empty($this->img)) { throw new \Exception(_('No image can be written to a text resources')); } if (!is_file($font)) { throw new \Exception(_("Font file does not exist:") . $font); } //获取颜色和透明度 if (is_array($color)) { $color = array_map('dechex', $color); foreach ($color as &$value) { $value = str_pad($value, 2, '0', STR_PAD_LEFT); } $color = '#' . implode('', $color); } elseif (!is_string($color) || 0 !== strpos($color, '#')) { throw new \Exception(_('Wrong color values')); } $col = substr($color, 0, 7); $alp = strlen($color) == 9 ? substr($color, -2) : 0; //获取文字信息 $draw = new \ImagickDraw(); $draw->setFont(realpath($font)); $draw->setFontSize($size); $draw->setFillColor($col); $draw->setFillAlpha(1 - hexdec($alp) / 127); $draw->setTextAntialias(true); $draw->setStrokeAntialias(true); $metrics = $this->img->queryFontMetrics($draw, $text); /* 计算文字初始坐标和尺寸 */ $x = 0; $y = $metrics['ascender']; $w = $metrics['textWidth']; $h = $metrics['textHeight']; /* 设定文字位置 */ switch ($locate) { /* 右下角文字 */ case Image::IMAGE_WATER_SOUTHEAST: $x += $this->info['width'] - $w; $y += $this->info['height'] - $h; break; /* 左下角文字 */ /* 左下角文字 */ case Image::IMAGE_WATER_SOUTHWEST: $y += $this->info['height'] - $h; break; /* 左上角文字 */ /* 左上角文字 */ case Image::IMAGE_WATER_NORTHWEST: // 起始坐标即为左上角坐标,无需调整 break; /* 右上角文字 */ /* 右上角文字 */ case Image::IMAGE_WATER_NORTHEAST: $x += $this->info['width'] - $w; break; /* 居中文字 */ /* 居中文字 */ case Image::IMAGE_WATER_CENTER: $x += ($this->info['width'] - $w) / 2; $y += ($this->info['height'] - $h) / 2; break; /* 下居中文字 */ /* 下居中文字 */ case Image::IMAGE_WATER_SOUTH: $x += ($this->info['width'] - $w) / 2; $y += $this->info['height'] - $h; break; /* 右居中文字 */ /* 右居中文字 */ case Image::IMAGE_WATER_EAST: $x += $this->info['width'] - $w; $y += ($this->info['height'] - $h) / 2; break; /* 上居中文字 */ /* 上居中文字 */ case Image::IMAGE_WATER_NORTH: $x += ($this->info['width'] - $w) / 2; break; /* 左居中文字 */ /* 左居中文字 */ case Image::IMAGE_WATER_WEST: $y += ($this->info['height'] - $h) / 2; break; default: /* 自定义文字坐标 */ if (is_array($locate)) { list($posx, $posy) = $locate; $x += $posx; $y += $posy; } else { throw new \Exception(_('Position of the character type is not supported')); } } /* 设置偏移量 */ if (is_array($offset)) { $offset = array_map('intval', $offset); list($ox, $oy) = $offset; } else { $offset = intval($offset); $ox = $oy = $offset; } /* 写入文字 */ if ('gif' == $this->info['type']) { $img = $this->img->coalesceImages(); $this->img->destroy(); //销毁原图 do { $img->annotateImage($draw, $x + $ox, $y + $oy, $angle, $text); } while ($img->nextImage()); //压缩图片 $this->img = $img->deconstructImages(); $img->destroy(); //销毁零时图片 } else { $this->img->annotateImage($draw, $x + $ox, $y + $oy, $angle, $text); } $draw->destroy(); }
/** * Renders the CAPTCHA image based on the code using ImageMagick library. * @param string $code the verification code * @return string image contents in PNG format. */ protected function renderImageByImagick($code) { $backColor = $this->transparent ? new \ImagickPixel('transparent') : new \ImagickPixel('#' . dechex($this->backColor)); $foreColor = new \ImagickPixel('#' . dechex($this->foreColor)); $image = new \Imagick(); $image->newImage($this->width, $this->height, $backColor); $draw = new \ImagickDraw(); $draw->setFont($this->fontFile); $draw->setFontSize(30); $fontMetrics = $image->queryFontMetrics($draw, $code); $length = strlen($code); $w = (int) $fontMetrics['textWidth'] - 8 + $this->offset * ($length - 1); $h = (int) $fontMetrics['textHeight'] - 8; $scale = min(($this->width - $this->padding * 2) / $w, ($this->height - $this->padding * 2) / $h); $x = 10; $y = round($this->height * 27 / 40); for ($i = 0; $i < $length; ++$i) { $draw = new \ImagickDraw(); $draw->setFont($this->fontFile); $draw->setFontSize((int) (rand(26, 32) * $scale * 0.8)); $draw->setFillColor($foreColor); $image->annotateImage($draw, $x, $y, rand(-10, 10), $code[$i]); $fontMetrics = $image->queryFontMetrics($draw, $code[$i]); $x += (int) $fontMetrics['textWidth'] + $this->offset; } $image->setImageFormat('png'); return $image->getImageBlob(); }
/** * Renders the CAPTCHA image based on the code using ImageMagick library. * @param string $code the verification code * @param string $encoding character encoding * @return string image contents in PNG format. */ protected function mbRenderImageByImagick($code, $encoding) { $backColor = $this->transparent ? new \ImagickPixel('transparent') : new \ImagickPixel(sprintf('#%06x', $this->backColor)); $foreColor = new \ImagickPixel(sprintf('#%06x', $this->foreColor)); $image = new \Imagick(); $image->newImage($this->width, $this->height, $backColor); $draw = new \ImagickDraw(); $draw->setFont($this->mbFontFile); $draw->setFontSize(30); $fontMetrics = $image->queryFontMetrics($draw, $code); $length = mb_strlen($code, $encoding); $w = (int) $fontMetrics['textWidth'] + $this->mbOffset * ($length - 1); $h = (int) $fontMetrics['textHeight']; $scale = min(($this->width - $this->padding * 2) / $w, ($this->height - $this->padding * 2) / $h); $x = 8; // font size and angle $fontSize = (int) (30 * $scale * 0.9); $angle = 0; // base line $yBottom = $this->height - $this->padding * 4; $yTop = (int) ($h * $scale * 0.95) + $this->padding * 4; if ($yTop > $yBottom) { $yTop = $yBottom; } for ($i = 0; $i < $length; ++$i) { $letter = mb_substr($code, $i, 1, $encoding); $y = mt_rand($yTop, $yBottom); if (!$this->fixedAngle) { $angle = mt_rand(-15, 15); } $draw = new \ImagickDraw(); $draw->setFont($this->mbFontFile); $draw->setFontSize($fontSize); $draw->setFillColor($foreColor); $image->annotateImage($draw, $x, $y, $angle, $letter); $fontMetrics = $image->queryFontMetrics($draw, $letter); $x += (int) $fontMetrics['textWidth'] + $this->mbOffset; } $image->setImageFormat('png'); return $image->getImageBlob(); }