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 page_testfonts() { //load background $im = new Imagick(); $im->newimage(800, 10000, 'lightgray'); $y = 10; $i = 1; foreach ($im->queryFonts() as $font) { $insert_image = new Imagick(); $insert_image->newImage(600, 30, 'whitesmoke'); $insert_image->setImageFormat("png"); $draw = new ImagickDraw(); $draw->setFont($font); $draw->setFontSize(25); $draw->setFillColor(new ImagickPixel('black')); $draw->setgravity(imagick::GRAVITY_NORTH); $insert_image->annotateImage($draw, 0, 0, 0, $i . '.' . $font); $im->compositeImage($insert_image, $insert_image->getImageCompose(), 100, $y); $y += 30; $i++; } $im->setImageFormat('jpg'); header('Content-Type: image/jpg'); echo $im; }
/** * Draws a text string on the image in a specified location, with the * specified style information. * * @TODO: Need to differentiate between the stroke (border) and the fill * color, but this is a BC break, since we were just not providing a * border. * * @param string $text The text to draw. * @param integer $x The left x coordinate of the start of the * text string. * @param integer $y The top y coordinate of the start of the text * string. * @param string $font The font identifier you want to use for the * text. * @param string $color The color that you want the text displayed in. * @param integer $direction An integer that specifies the orientation of * the text. * @param string $fontsize Size of the font (small, medium, large, giant) */ public function text($string, $x, $y, $font = '', $color = 'black', $direction = 0, $fontsize = 'small') { $fontsize = Horde_Image::getFontSize($fontsize); try { $pixel = new ImagickPixel($color); } catch (ImagickPixelException $e) { throw new Horde_Image_Exception($e); } try { $draw = new ImagickDraw(); $draw->setFillColor($pixel); if (!empty($font)) { $draw->setFont($font); } $draw->setFontSize($fontsize); $draw->setGravity(Imagick::GRAVITY_NORTHWEST); } catch (ImagickDrawException $e) { throw new Horde_Image_Exception($e); } try { $this->_imagick->annotateImage($draw, $x, $y, $direction, $string); } catch (ImagickException $e) { throw new Horde_Image_Exception($e); } $draw->destroy(); }
/** * (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); } }
protected function drawText($text, $size, $fontFile, $x, $y, $color, $opacity, $angle) { $draw = new $this->drawClass(); $draw->setFont($fontFile); $draw->setFontSize($size); $draw->setFillColor($this->getColor($color, $opacity)); $this->image->annotateImage($draw, $x, $y, -$angle, $text); return $this; }
/** * {@inheritdoc} */ public function text($string, AbstractFont $font, PointInterface $position, $angle = 0, $width = null) { 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); if ($width !== null) { $string = $this->wrapText($string, $text, $angle, $width); } // $this->imagick->annotateImage( // $text, $position->getX() + $x1 + $xdiff, // $position->getY() + $y2 + $ydiff, $angle, $string // ); $deltaX = $info['characterWidth'] * sin(deg2rad($angle)); $deltaY = $info['characterHeight']; $posX = $position->getX() - $deltaX; if ($posX < 0) { $posX = 0; } $this->imagick->annotateImage($text, $posX, $position->getY() + $deltaY, $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; }
/** * 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); }
/** * Execute a text * * @param string $text * @param int $offsetX * @param int $offsetY * @param float $opacity * @param int $color * @param int $size * @param string $font_file * * @return static */ public function text($text, $offsetX = 0, $offsetY = 0, $opacity = 1.0, $color = 0x0, $size = 12, $font_file = null) { $draw = new \ImagickDraw(); $textColor = sprintf('rgb(%u,%u,%u)', $color >> 16 & 0xff, $color >> 8 & 0xff, $color & 0xff); $draw->setFillColor(new \ImagickPixel($textColor)); if ($font_file) { $draw->setFont($this->alias->resolve($font_file)); } $draw->setFontSize($size); $draw->setFillOpacity($opacity); $draw->setGravity(\Imagick::GRAVITY_NORTHWEST); $this->_image->annotateImage($draw, $offsetX, $offsetY, 0, $text); $draw->destroy(); return $this; }
function AboveText() { $abovetextimage = new Imagick(); $draw = new ImagickDraw(); $pixel = new ImagickPixel('transparent'); $abovetextimage->newImage(600, 600, $pixel); $draw->setFillColor('black'); $draw->setFont('Bookman-DemiItalic'); $draw->setFontSize(20); $myfirstName = explode(" ", $this->{$userName}); $fname = $myfirstName[0]; $abovetextimage->annotateImage($draw, 5, 20, 0, "{$this}->{$name} has a secret crush on {$fname}"); $abovetextimage->setImageFormat('png'); $abovetextimage->writeImage("abovetext.png"); $this->{$aboveText} = imagecreatefrompng("abovetext.png"); }
protected function draw_text($text, $size, $font_file, $x, $y, $color, $opacity, $angle) { $draw = new $this->draw_class(); $draw->setFont($font_file); $draw->setFontSize($size); $draw->setFillColor($this->get_color($color, $opacity)); if ($this->multiframe()) { $this->image = $this->image->coalesceImages(); foreach ($this->image as $frame) { $frame->annotateImage($draw, $x, $y, -$angle, $text); } } else { $this->image->annotateImage($draw, $x, $y, -$angle, $text); } return $this; }
/** * 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 TextOverlay() { $textimage = new Imagick(); $draw = new ImagickDraw(); $pixel = new ImagickPixel('transparent'); /* New image */ $textimage->newImage(600, 600, $pixel); /* Black text */ $draw->setFillColor('blue'); /* Font properties */ $draw->setFont('Bookman-DemiItalic'); $draw->setFontSize(20); /* Create text */ $textimage->annotateImage($draw, 5, 20, 0, "{$name} has a secret CRUSH on YOU!"); /* Give image a format */ $textimage->setImageFormat('png'); $textimage->writeImage("rounded3.png"); $top_image3 = imagecreatefrompng("rounded3.png"); }
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; }
/** * Creates image with text * @param int $sizeX * @param int $sizeY * @param string $text * @param string $generator * @return \Imagick */ public function mkCapcha($sizeX, $sizeY, $text, $generator = self::METHOD_DEFAULT) { // init image $image = new \Imagick(); $image->newImage($sizeX, $sizeY, new \ImagickPixel('white')); $image->setImageFormat('png'); switch ($generator) { case self::METHOD_GRAYNOISE: $draw = new \ImagickDraw(); $draw->setFontSize(35); $draw->setFontWeight(900); $draw->setGravity(\imagick::GRAVITY_CENTER); $image->addNoiseImage(\imagick::NOISE_LAPLACIAN); $image->annotateImage($draw, 0, 0, 0, $text); $image->charcoalImage(2, 1.5); $image->addNoiseImage(\imagick::NOISE_LAPLACIAN); $image->gaussianBlurImage(1, 1); break; case self::METHOD_GRAYBLUR: $draw = new \ImagickDraw(); $order = []; for ($i = 0; $i < strlen($text); $i++) { $order[$i] = $i; } shuffle($order); for ($j = 0; $j < 2; $j++) { shuffle($order); $image->gaussianBlurImage(15, 3); for ($n = 0; $n < strlen($text); $n++) { $i = $order[$n]; $draw->setFont(__DIR__ . '/Capcha/DejaVuSans.ttf'); $draw->setFontSize($j ? rand($sizeY * 3 / 5, $sizeY * 5 / 6) : rand($sizeY * 4 / 6, $sizeY * 5 / 6)); $draw->setFontWeight(rand(100, 900)); $draw->setGravity(\imagick::GRAVITY_CENTER); $image->annotateImage($draw, ($i - strlen($text) / 2) * $sizeX / (strlen($text) + 2.3), 0, rand(-25, 25), $text[$i]); $image->gaussianBlurImage(1, 1); } } break; } return $image; }
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; }
/** * 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(); }
$ref->addAttribute("pagina", $pagina_actual); $cp = 'SELECT foto, pc.titulo FROM flores_productos_categoria LEFT JOIN flores_producto_contenedor AS pc USING(codigo_producto) LEFT JOIN flores_producto_variedad USING(codigo_producto) WHERE codigo_categoria=' . $f['codigo_categoria'] . ' GROUP BY codigo_producto'; $rp = db_consultar($cp); $pagina_actual += 1 + mysql_numrows($rp); while ($fp = mysql_fetch_assoc($rp)) { if (!file_exists('catalogo360/pages/' . $fp['foto'])) { $im = new Imagick('IMG/i/' . $fp['foto']); $im->setCompression(Imagick::COMPRESSION_JPEG); $im->setCompressionQuality(90); $im->setImageFormat('jpeg'); $im->stripImage(); $draw = new ImagickDraw(); $pixel = new ImagickPixel('gray'); $pixel->setColor('black'); $draw->setFont('flower.ttf'); $draw->setFontSize(30); $im->thumbnailImage(350, 525, false); $im->annotateImage($draw, 10, 45, 0, $fp['titulo']); $im->writeImage('catalogo360/pages/' . $fp['foto']); $im->clear(); $im->destroy(); unset($im); } $XMLP->pages->addChild('page', 'pages/' . $fp['foto']); } } file_put_contents('catalogo360/marcadores.xml', $XML->asXML()); file_put_contents('catalogo360/config.xml', $XMLP->asXML()); echo $XML->asXML(); echo $XMLP->asXML(); exit;
/** * Function to get a single lab picture binary data. Picture can be resized * if width/height is less than real ones. Aspect ratio is always guaranteed. * * @param Lab $lab Lab * @param int $id Picture ID * @param int $height Height of the resized picture * @param int $width Width of the resized picture * @return Array Lab picture (JSend data) */ function apiGetLabPictureData($lab, $id, $width, $height) { $output['code'] = 200; $output['encoding'] = 'image/png'; if (isset($lab->getPictures()[$id])) { $output['data'] = resizeImage($lab->getPictures()[$id]->getData(), $width, $height); } else { // Generate an error image $draw = new ImagickDraw(); $draw->setFillColor('black'); $draw->setFontSize(30); $pixel = new ImagickPixel('white'); $img = new Imagick(); $img->newImage(800, 75, $pixel); $img->setImageFormat('png'); $img->annotateImage($draw, 10, 45, 0, 'ERROR: ' . $GLOBALS['messages'][60029]); $output['data'] = resizeImage($img->getImageBlob(), $width, $height); } return $output; }
function waterMarkFont() { if ($this->param['water_mark_color']) { $color = $this->param['water_mark_color']; } else { $color = '#000000'; } $r = hexdec(substr($color, 1, 2)); $g = hexdec(substr($color, 3, 2)); $b = hexdec(substr($color, 5, 2)); $draw = new ImagickDraw(); $draw->setFillColor(new ImagickPixel($color)); //设置填充颜色 $draw->setFont($this->param['water_mark_font']); //设置文本字体,要求ttf或者ttc字体,可以绝对或者相对路径 $draw->setFontSize($this->param['water_mark_fontsize']); //设置字号 switch ($this->param['water_mark_pos']) { case 0: case 1: $gravity = Imagick::GRAVITY_NORTHWEST; //'NorthWest'; break; case 2: $gravity = Imagick::GRAVITY_NORTH; //'North'; break; case 3: $gravity = Imagick::GRAVITY_NORTHEAST; //'NorthEast'; break; case 4: $gravity = Imagick::GRAVITY_WEST; //'West'; break; case 5: $gravity = Imagick::GRAVITY_CENTER; //'Center'; break; case 6: $gravity = Imagick::GRAVITY_EAST; //'East'; break; case 7: $gravity = Imagick::GRAVITY_SOUTHWEST; //'SouthWest'; break; case 8: $gravity = Imagick::GRAVITY_SOUTH; //'South'; break; case 9: $gravity = Imagick::GRAVITY_SOUTHEAST; break; } $draw->setGravity($gravity); if ($this->image_type == 'GIF') { $color_transparent = new ImagickPixel("transparent"); $dest = new Imagick(); foreach ($this->image as $frame) { $page = $frame->getImagePage(); $tmp = new Imagick(); $tmp->newImage($page['width'], $page['height'], $color_transparent, 'gif'); $tmp->compositeImage($frame, Imagick::COMPOSITE_OVER, $page['x'], $page['y']); $tmp->annotateImage($draw, 0, 0, $this->param['water_mark_angle'], $this->param['water_mark_string']); $dest->addImage($tmp); $dest->setImagePage($tmp->getImageWidth(), $tmp->getImageHeight(), 0, 0); $dest->setImageDelay($frame->getImageDelay()); $dest->setImageDispose($frame->getImageDispose()); } $dest->coalesceImages(); $this->image->destroy(); $this->image = $dest; } else { if ($this->param['water_mark_opacity']) { $draw->setFillOpacity($this->param['water_mark_opacity'] / 100); } $this->image->annotateImage($draw, 0, 0, $this->param['water_mark_angle'], $this->param['water_mark_string']); } }
function fl_regenerate_sprite_cache($sheet_id, $sprites, $out_image_file_type = "png") { if (defined('fl_test_environment')) { fllog('! fl_regenerate_sprite_cache: ' . flcache . $sheet_id . '.' . $out_image_file_type); } $biggest_w = 0; $biggest_h = 0; $rects = array(); $i = 0; foreach ($sprites as &$sprite) { $i++; //var_dump( $sprite ); if (!isset($sprite['size'])) { $sprite['size'] = 14; } if (!isset($sprite['color'])) { $sprite['color'] = '#000000'; } if (!isset($sprite['font'])) { fllog('Font not set for sprite id `' . $sheet_id . '` sprite #' . $i); continue; } //var_dump($sprite); $sprite['dimension'] = fl_query_font_render_size(flres(flvault . $sprite['font']), intval($sprite['size']), $sprite['color'], $sprite['text']); $sprite['w'] = $sprite['dimension']['w']; $sprite['h'] = $sprite['dimension']['h']; $w = intval($sprite['w']); $h = intval($sprite['h']); if ($w > $biggest_w) { $biggest_w = $w; } if ($h > $biggest_h) { $biggest_h = $h; } $rects[$i - 1] = $sprite; } // echo 'Packing rects..'; $packed = PackRect($rects, fl_biggest_w, fl_biggest_h, $w, $h, fl_pack_precision, fl_pack_precision); $i = 0; try { $total = count($rects); $c = new Imagick(); //var_dump($packed); $c->newImage(intval($packed['width']), intval($packed['height']), "transparent", $out_image_file_type); $css = ''; $d = array(); foreach ($packed as $k => $sprite) { if (!is_numeric($k)) { continue; } else { $d = new ImagickDraw(); $d->setFont(fl_get_fontfile($sprite['font'])); $d->setFontSize(floatval($sprite['size'])); $d->setGravity(Imagick::GRAVITY_NORTHWEST); $d->setFillColor($sprite['color']); $result = $c->annotateImage($d, floatval($sprite['x']), floatval($sprite['y']), 0, $sprite['text']); $d->clear(); $d->destroy(); } } $c->setImageFormat(strtoupper($out_image_file_type)); $c->writeImage(flres(flcache . $sheet_id . '.' . $out_image_file_type)); $c->clear(); $c->destroy(); } catch (Exception $e) { echo $e->getMessage(); } fl_make_sheet($sheet_id, $packed, $out_image_file_type); //die; }
public function addWatermarkTextMosaic($text = "Copyright", $font = "Courier", $size = 20, $color = "grey70", $maskColor = "grey30", $position = \Imagick::GRAVITY_SOUTHEAST) { $watermark = new \Imagick(); $draw = new \ImagickDraw(); $watermark->newImage(140, 80, new \ImagickPixel('none')); $draw->setFont($font); $draw->setFillColor('grey'); $draw->setFillOpacity(0.4); $draw->setGravity(\Imagick::GRAVITY_NORTHWEST); $watermark->annotateImage($draw, 10, 10, 0, $text); $draw->setGravity(\Imagick::GRAVITY_SOUTHEAST); $watermark->annotateImage($draw, 5, 15, 0, $text); for ($w = 0; $w < $this->getImage()->getImageWidth(); $w += 140) { for ($h = 0; $h < $this->getImage()->getImageHeight(); $h += 80) { $this->getImage()->compositeImage($watermark, \Imagick::COMPOSITE_OVER, $w, $h); } } }
function LoadPhoto($cont, $idx) { $uploaddir = '../attached_file/'; $microtime = microtime(); $max_size = 5 * 1024 * 1024; $max_image_width = 5000; $max_image_height = 5000; $error = ''; $max_side_px = 800; $filetypes = array('image/jpeg'); //'image/png', 'image/bmp', 'image/gif' $extens = array('jpg', 'jpeg'); //'png', 'gif', 'bmp' $id_file = substr($microtime, 11) . substr($microtime, 2, 6); $ext = strtolower(substr($cont['name'], strrpos($cont['name'], ".") + 1)); if (is_uploaded_file($cont['tmp_name'])) { #Проверка веса if ($cont['size'] == 0) { $error = 'Файл 0кб.'; } elseif ($cont['size'] > $max_size) { $error = 'Размер превышает 5мб.'; } else { #Проверка типов if (in_array($cont['type'], $filetypes) and in_array($ext, $extens)) { $size = GetImageSize($cont['tmp_name']); #Проверка размера if ($size && $size[0] < $max_image_width && $size[1] < $max_image_height) { #Загрузка if (move_uploaded_file($cont['tmp_name'], $uploaddir . $id_file . '.' . $ext)) { $link = dbh::connect(); $sql = "INSERT INTO `attached_file` (id_file,ext,idx) VALUES('{$id_file}','{$ext}','{$idx}')"; $res = mysql_query($sql); dbh::disconnect($link); #Инициализируем максимальную сторону фотки, и принимаем решение делаем ли ресайз $x = $max_side_px; $y = $max_side_px; if ($size[0] > $size[1]) { $y = 0; } else { $x = 0; } $rex = $size[0] > $size[1] ? $size[0] : $size[1]; $rex = $rex > $max_side_px ? 1 : 0; #Фото без водяного знака, обрезаем большую сторону до 800, делает Quality=70% $img_no_mark = new Imagick($uploaddir . $id_file . '.' . $ext); $img_no_mark->setImageCompression(imagick::COMPRESSION_JPEG); $img_no_mark->setImageCompressionQuality(70); if ($rex) { $img_no_mark->scaleImage($x, $y); } $img_no_mark->writeImage($uploaddir . $id_file . '_s.' . $ext); $img_no_mark->destroy(); #Фото с водяным знаком, обрезаем большую сторону до 800 $img = new Imagick($uploaddir . $id_file . '.' . $ext); $mark = new Imagick($uploaddir . 'mark.png'); $rgs = new Imagick($uploaddir . 'rgs.png'); if ($rex) { $img->scaleImage($x, $y); } $w = $img->getImageWidth() - 371; $h = $img->getImageHeight() - 150; $wrgs = $img->getImageWidth() - 120; $hrgs = $h - 50; $textWrite = 'застраховано'; $wtxt = $img->getImageWidth() - 120; $htxt = $hrgs - 10; $fontColor = '#FFFFFF'; $fontSize = 18; $colorPix = new ImagickPixel($fontColor); $draw = new ImagickDraw(); $draw->setFontSize($fontSize); $draw->setFillColor($colorPix); $img->annotateImage($draw, $wtxt, $htxt, 0, $textWrite); $img->compositeImage($mark, imagick::COMPOSITE_OVER, $w, $h); $img->compositeImage($rgs, imagick::COMPOSITE_OVER, $wrgs, $hrgs); $img->writeImage($uploaddir . $id_file . '.' . $ext); #Так же делаем привью if ($size[0] > $size[1]) { $img->scaleImage(0, 150); } else { $img->scaleImage(150, 0); } $img->writeImage($uploaddir . $id_file . '_p.' . $ext); $img->destroy(); } else { $error = $cont['tmp_name'] . ' ' . $uploaddir . $id_file . $ext; } } else { $error = 'Превышен размер ' . $max_image_width . 'x' . $max_image_height . '.'; } } else { $error = 'Файл имеет недопустимый формат! Разрешены только jpg, jpeg.'; } } } else { $error = 'Файл пустой.'; } if ($error) { $error = 'Ошибка загрузки файла ' . $cont['name'] . '! ' . $error . '<br><br>'; } return $error; }
function generate_final_video_frames($converted_avatars, $uid, $dir = 'data', $videos_frames) { include get_template_directory() . '/video_libs/libs.php'; $frames = array(); $i = 1; $converted_path = $dir . "/{$uid}/frames"; if (!file_exists("{$converted_path}")) { exec("mkdir -p {$converted_path}"); } exec("chmod 777 -R {$converted_path}"); exec("rm -rf {$converted_path}/*"); #include get_template_directory() . '/video_libs/data.php'; /*include get_template_directory() . '/video_libs/data_live.php'; $videos_frames = get_data_videos($_REQUEST['uid'], $_REQUEST['eid']);*/ foreach ($videos_frames as $key => $value) { $name = generate_filename($i); $filename = $value->imageFrame; $curr_frame = "{$converted_path}/{$name}"; $frames[] = $curr_frame; $text_objs = isset($value->text) ? $value->text : array(); $image_objs = isset($value->imageFace) ? $value->imageFace : array(); if (array_key_exists($filename, $converted_avatars) && !empty($converted_avatars[$filename])) { if (!empty($image_objs)) { foreach ($image_objs as $image_obj) { $order = $image_obj->order; if ($order == 'back') { $msg = exec("convert {$converted_avatars[$filename]} {$filename} -composite {$curr_frame}"); } else { $msg = exec("convert {$filename} {$converted_avatars[$filename]} -composite {$curr_frame}"); } } } } else { exec("cp {$filename} {$curr_frame}"); } $w = 210; if (!empty($text_objs)) { foreach ($text_objs as $text_obj) { $picin = new Imagick($curr_frame); $draw = new ImagickDraw(); $draw->setTextEncoding('utf-8'); $draw->setFillColor("rgba(255, 255, 255, {$text_obj->opacity})"); $draw->setFont($text_obj->font); $draw->setFontSize($text_obj->size); $positions = explode(',', $text_obj->position); //list($lines, $lineHeight)= wordWrapAnnotation($picin, $draw, $text_obj->text, $w-10); if (!empty($text_obj->break) && $text_obj->break == 'yes') { $y = $positions[1]; $line_height = 55; $str = wordwrap($text_obj->text, 19, "\n"); $str_array = explode("\n", $str); foreach ($str_array as $line) { $picin->annotateImage($draw, $positions[0], $y, 0, $line); $y += $line_height; } } else { $picin->annotateImage($draw, $positions[0], $positions[1], 0, $text_obj->text); } //$picin->annotateImage($draw, $positions[0], $positions[1], 0, $text_obj->text); //$picin->annotateImage($draw, $positions[0], $positions[1], 0, $lines); $picin->writeimage($curr_frame); /*if( strpos($filename, '110.png')){ echo '<pre>'; print_r($image_obj); echo '</pre>'; echo 'aaaa';die; }*/ } } $i++; } return $frames; }
/** * 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; }
/** * 图像添加文字 * @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(); }
public function addFont($text, $font, $startX = 0, $startY = 12, $color = 'black', $fontSize = 12, $alpha = 1, $degree = 0) { if (!$text) { return $this; } if (!is_readable($font)) { throw new ImageUtilityException('ImageImagickUtility 錯誤!', '參數錯誤,font:' . $font, '字型檔案不存在!'); } if (!($startX >= 0 && $startY >= 0)) { throw new ImageUtilityException('ImageImagickUtility 錯誤!', '起始點錯誤,startX:' . $startX . ',startY:' . $startY, '水平、垂直的起始點一定要大於 0!'); } if (!is_string($color)) { throw new ImageUtilityException('ImageImagickUtility 錯誤!', '色碼錯誤!', '請確認色碼格式,目前只支援 字串HEX 格式!'); } if (!($fontSize > 0)) { throw new ImageUtilityException('ImageImagickUtility 錯誤!', '參數錯誤,fontSize:' . $fontSize, '文字大小一定要大於 0!'); } if (!($alpha && is_numeric($alpha) && $alpha >= 0 && $alpha <= 1)) { throw new ImageUtilityException('ImageImagickUtility 錯誤!', '參數錯誤,alpha:' . $alpha, '參數 alpha 一定要是 0 或 1!'); } if (!is_numeric($degree %= 360)) { throw new ImageUtilityException('ImageImagickUtility 錯誤!', '角度一定要是數字,degree:' . $degree, '請確認 GD 函式庫中是否有支援 imagerotate 函式!'); } if (!($draw = $this->_createFont($font, $fontSize, $color, $alpha))) { throw new ImageUtilityException('ImageImagickUtility 錯誤!', ' Create 文字物件失敗', '請程式設計者確認狀況!'); } if ($this->format == 'gif') { $newImage = new Imagick(); $newImage->setFormat($this->format); $imagick = $this->image->clone()->coalesceImages(); do { $temp = new Imagick(); $temp->newImage($this->dimension['width'], $this->dimension['height'], new ImagickPixel('transparent')); $temp->compositeImage($imagick, imagick::COMPOSITE_DEFAULT, 0, 0); $temp->annotateImage($draw, $startX, $startY, $degree, $text); $newImage->addImage($temp); $newImage->setImageDelay($imagick->getImageDelay()); } while ($imagick->nextImage()); } else { $newImage = $this->image->clone(); $newImage->annotateImage($draw, $startX, $startY, $degree, $text); } return $this->_updateImage($newImage); }
/** * Renders a string into the image * * @param Imagick $image * @param ImagickDraw $font * @param int $x * @param int $y * @param string $string * @param ImagickPixel $color * @return bool */ function zp_writeString($image, $font, $x, $y, $string, $color) { $font->setStrokeColor($color); return $image->annotateImage($font, $x, $y + $image->getImageHeight() / 2, 0, $string); }
/** * 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(); }
<?php // Create objects $image = new Imagick('../files/images/userbar_old.png'); // Watermark text // Create a new drawing palette $draw = new ImagickDraw(); // Set font properties $draw->setFont('../files/fonts/visitor.ttf'); $draw->setFontSize(10); $draw->setFillColor('white'); $text = ""; if (isset($_GET['user'])) { $text = $_GET['user']; } // Position text at the bottom-right of the image $draw->setGravity(Imagick::GRAVITY_EAST); $image->annotateImage($draw, 8, 0, 0, $text); // Set output image format $image->setImageFormat('png'); // Output the new image header('Content-type: image/png'); echo $image;