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 getImagineImage(ImagineInterface $imagine, FontCollection $fontCollection, $width, $height) { $fontPath = $fontCollection->getFontById($this->font)->getPath(); if ($this->getAbsoluteSize() !== null) { $fontSize = $this->getAbsoluteSize(); } elseif ($this->getRelativeSize() !== null) { $fontSize = (int) $this->getRelativeSize() / 100 * $height; } else { throw new \LogicException('Either relative or absolute watermark size must be set!'); } if (true || !class_exists('ImagickDraw')) { // Fall back to ugly image. $palette = new \Imagine\Image\Palette\RGB(); $font = $imagine->font($fontPath, $fontSize, $palette->color('#000')); $box = $font->box($this->getText()); $watermarkImage = $imagine->create($box, $palette->color('#FFF')); $watermarkImage->draw()->text($this->text, $font, new \Imagine\Image\Point(0, 0)); } else { // CURRENTLY DISABLED. // Use nicer Imagick implementation. // Untested! // @todo Test and implement it! $draw = new \ImagickDraw(); $draw->setFont($fontPath); $draw->setFontSize($fontSize); $draw->setStrokeAntialias(true); //try with and without $draw->setTextAntialias(true); //try with and without $draw->setFillColor('#fff'); $textOnly = new \Imagick(); $textOnly->newImage(1400, 400, "transparent"); //transparent canvas $textOnly->annotateImage($draw, 0, 0, 0, $this->text); //Create stroke $draw->setFillColor('#000'); //same as stroke color $draw->setStrokeColor('#000'); $draw->setStrokeWidth(8); $strokeImage = new \Imagick(); $strokeImage->newImage(1400, 400, "transparent"); $strokeImage->annotateImage($draw, 0, 0, 0, $this->text); //Composite text over stroke $strokeImage->compositeImage($textOnly, \Imagick::COMPOSITE_OVER, 0, 0, \Imagick::CHANNEL_ALPHA); $strokeImage->trimImage(0); //cut transparent border $watermarkImage = $imagine->load($strokeImage->getImageBlob()); //$strokeImage->resizeImage(300,0, \Imagick::FILTER_CATROM, 0.9, false); //resize to final size } return $watermarkImage; }
/** * Draws font to given image at given position * * @param Image $image * @param integer $posx * @param integer $posy * @return void */ public function applyToImage(Image $image, $posx = 0, $posy = 0) { // build draw object $draw = new \ImagickDraw(); $draw->setStrokeAntialias(true); $draw->setTextAntialias(true); // set font file if ($this->hasApplicableFontFile()) { $draw->setFont($this->file); } else { throw new \Intervention\Image\Exception\RuntimeException("Font file must be provided to apply text to image."); } // parse text color $color = new Color($this->color); $draw->setFontSize($this->size); $draw->setFillColor($color->getPixel()); // align horizontal switch (strtolower($this->align)) { case 'center': $align = \Imagick::ALIGN_CENTER; break; case 'right': $align = \Imagick::ALIGN_RIGHT; break; default: $align = \Imagick::ALIGN_LEFT; break; } $draw->setTextAlignment($align); // align vertical if (strtolower($this->valign) != 'bottom') { // calculate box size $dimensions = $image->getCore()->queryFontMetrics($draw, $this->text); // corrections on y-position switch (strtolower($this->valign)) { case 'center': case 'middle': $posy = $posy + $dimensions['textHeight'] * 0.65 / 2; break; case 'top': $posy = $posy + $dimensions['textHeight'] * 0.65; break; } } // apply to image $image->getCore()->annotateImage($draw, $posx, $posy, $this->angle * -1, $this->text); }
public function build() { // Prepage image $this->_canvas = new Imagick(); $this->_canvas->newImage(self::WIDTH, self::HEIGHT, new ImagickPixel("white")); $color['line'] = new ImagickPixel("rgb(216, 76, 64)"); $color['text'] = new ImagickPixel("rgb(16, 35, 132)"); $color['karma'] = new ImagickPixel("rgb(116, 194, 98)"); $color['force'] = new ImagickPixel("rgb(37, 168, 255)"); $color['bottom_bg'] = new ImagickPixel("rgb(255, 244, 224)"); $color['bg'] = new ImagickPixel("white"); $color['neutral'] = new ImagickPixel("rgb(200, 200, 200)"); $color['habr'] = new ImagickPixel("rgb(83, 121, 139)"); // Prepare canvas for drawing main graph $draw = new ImagickDraw(); $draw->setStrokeAntialias(true); $draw->setStrokeWidth(2); // Prepare values for drawing main graph define('PADDING', 10); // Draw bottom bg define('TOP_SPACER', 10); $draw = new ImagickDraw(); $draw->setFillColor($color['bg']); $draw->setStrokeColor($color['habr']); $draw->polyline(array(array('x' => 0, 'y' => 0), array('x' => self::WIDTH - 1, 'y' => 0), array('x' => self::WIDTH - 1, 'y' => self::HEIGHT - 1), array('x' => 0, 'y' => self::HEIGHT - 1), array('x' => 0, 'y' => 0))); $this->_canvas->drawImage($draw); $draw->destroy(); // Draw texts $draw = new ImagickDraw(); $draw->setTextAlignment(Imagick::ALIGN_CENTER); $draw->setTextAntialias(true); $draw->setFillColor($color['karma']); $draw->polyline(array(array('x' => 1, 'y' => 1), array('x' => self::WIDTH / 2, 'y' => 1), array('x' => self::WIDTH / 2, 'y' => self::HEIGHT - 2), array('x' => 1, 'y' => self::HEIGHT - 2), array('x' => 1, 'y' => 1))); $draw->setFillColor($color['bg']); $draw->setFontSize(11); $draw->setFont(realpath('stuff/consolab.ttf')); $draw->annotation(self::WIDTH / 4, 11, sprintf('%01.2f', $this->_karma)); $draw->setFillColor($color['force']); $draw->polyline(array(array('x' => self::WIDTH / 2 + 1, 'y' => 1), array('x' => self::WIDTH - 2, 'y' => 1), array('x' => self::WIDTH - 2, 'y' => self::HEIGHT - 2), array('x' => self::WIDTH / 2 + 1, 'y' => self::HEIGHT - 2), array('x' => self::WIDTH / 2 + 1, 'y' => 1))); $draw->setFillColor($color['bg']); $draw->annotation(self::WIDTH / 4 * 3, 11, sprintf('%01.2f', $this->_habraforce)); $this->_canvas->drawImage($draw); $draw->destroy(); return true; }
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); }
function imageGeometryReset() { $draw = new \ImagickDraw(); $draw->setFont("../fonts/Arial.ttf"); $draw->setFontSize(48); $draw->setStrokeAntialias(true); $draw->setTextAntialias(true); $draw->setFillColor('#ff0000'); $textOnly = new \Imagick(); $textOnly->newImage(600, 300, "rgb(230, 230, 230)"); $textOnly->setImageFormat('png'); $textOnly->annotateImage($draw, 30, 40, 0, 'Your Text Here'); $textOnly->trimImage(0); $textOnly->setImagePage($textOnly->getimageWidth(), $textOnly->getimageheight(), 0, 0); $distort = array(180); $textOnly->setImageVirtualPixelMethod(Imagick::VIRTUALPIXELMETHOD_TRANSPARENT); $textOnly->setImageMatte(true); $textOnly->distortImage(Imagick::DISTORTION_ARC, $distort, false); $textOnly->setformat('png'); header("Content-Type: image/png"); echo $textOnly->getimageblob(); }
/** * Show image with error text. * * @param string $text * @param int $width * @param int $height */ public static function showError($text, $width, $height) { $canvas = new Imagick(); $canvas->newImage($width, $height, new ImagickPixel("white")); $draw = new ImagickDraw(); $draw->setFillColor(new ImagickPixel("white")); $draw->setStrokeColor(new ImagickPixel("black")); $draw->polyline(array(array('x' => 0, 'y' => 0), array('x' => $width - 1, 'y' => 0), array('x' => $width - 1, 'y' => $height - 1), array('x' => 0, 'y' => $height - 1), array('x' => 0, 'y' => 0))); $canvas->drawImage($draw); $draw->destroy(); $draw = new ImagickDraw(); $draw->setFillColor(new ImagickPixel("black")); $draw->setFontSize(12); $draw->setTextAlignment(Imagick::ALIGN_CENTER); $draw->setTextAntialias(true); $draw->setFont(realpath('stuff/consolab.ttf')); $draw->annotation($width / 2, $height / 2, $text); $canvas->drawImage($draw); $canvas->setImageFormat('png'); header("Content-Type: image/png"); echo $canvas; $draw->destroy(); $canvas->clear(); $canvas->destroy(); exit; }
function GetView() { global $TMP_PATH; $tmp_file = ADEI::GetTmpFile(); $im = new Imagick(); $tmp = new Imagick(); $image = new Imagick(); $final = new Imagick(); $with_axes = new Imagick(); $output = new Imagick(); $tick = new ImagickDraw(); $ceiling = new ImagickDraw(); $color = new ImagickPixel('#666666'); $background = new ImagickPixel('none'); // Transparent date_default_timezone_set('UTC'); $servername = "localhost"; $username = "******"; $password = "******"; $dbname = "HDCP10"; $req = $this->req->CreateGroupRequest(); $req = $this->req->CreateDataRequest(); $fstart = $req->GetProp("view_pb_start", 0); $width = $req->GetProp("control_width", 800); $height = $req->GetProp("control_height", 600); $height = $height - 180; // 60px for the xaxis (50px) $start = 1367366400000000.0; // GMT: Wed, 01 May 2013 00:00:00 GMT $end = 1367452800000000.0; // GMT: Thu, 02 May 2013 00:00:00 GMT //$end = 1367539200000000; // GMT: Fri, 03 May 2013 00:00:00 GMT $current = $start; $step = 3600000000.0; try { $conn = new PDO("mysql:host={$servername};dbname={$dbname}", $username, $password); // set the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); while (true) { if ($current >= $end) { break; } $start_interval = $current; $end_interval = $start_interval + $step; $sql = "SELECT img_id, image, timestamp FROM Profiles_060_WTH_STATIC_EL90_Images_Stitch_Im1_3600 WHERE timestamp >= " . $start_interval . " AND timestamp < " . $end_interval; $stmt = $conn->query($sql); $row = $stmt->fetchObject(); if ($row == false) { $im->newImage($width, $height - $height * 20 / 100, "white"); } else { if (is_null($row->image)) { $im->newImage($width, $height - $height * 20 / 100, "white"); } else { $im->readimageblob($row->image); $im->resizeImage($width, $height - $height * 20 / 100, Imagick::FILTER_LANCZOS, 1); } } #$text = date('H:s', ($current / 1000000)); #$draw = new ImagickDraw(); $tick = new ImagickDraw(); $ceiling = new ImagickDraw(); /* Font properties */ #$draw->setFont('Arial'); #$draw->setFontSize(200); #$draw->setFillColor($color); #$draw->setStrokeAntialias(true); #$draw->setTextAntialias(true); /* Get font metrics */ #$metrics = $image->queryFontMetrics($draw, $text); /* Create text */ #$draw->annotation(0, $metrics['ascender']+20, $text); $tick->setStrokeWidth(10); $tick->setStrokeColor($color); $tick->setFillColor($color); $tick->line(0, 0, 0, 20); //imageline($image, $width/2, 0, $width/2, 50, $color); $ceiling->setStrokeColor($color); $ceiling->setFillColor($color); $ceiling->line(0, 0, $width, 0); /* Create image */ $image->newImage($width, 20, $background); $image->setImageFormat('png'); #$image->drawImage($draw); $image->drawImage($tick); $image->drawImage($ceiling); $im->addImage($image); $im->resetIterator(); $tmp = $im->appendImages(true); $final->addImage($tmp); $current = $end_interval; $im->clear(); $image->clear(); $tmp->clear(); $tick->clear(); $ceiling->clear(); } } catch (PDOException $e) { //echo "Connection failed: " . $e->getMessage(); } /* Append the images into one */ $final->resetIterator(); $combined = $final->appendImages(false); /* Output the image */ $combined->setImageFormat("png"); $combined->resizeImage($width, $height - $height * 20 / 100, Imagick::FILTER_LANCZOS, 1); $draw = new ImagickDraw(); /* Font properties */ $draw->setFont('Arial'); $draw->setFontSize(12); $draw->setFillColor($color); $draw->setStrokeAntialias(true); $draw->setTextAntialias(true); $runner = $start; $axis_interval = $width / 24; $i = 0; while ($runner < $end) { $text = date('H:s', $runner / 1000000); $metrics = $image->queryFontMetrics($draw, $text); $draw->annotation($i * $axis_interval, $metrics['ascender'] + 20, $text); $runner = $runner + $step; $i++; } $xaxis = new Imagick(); $xaxis->newImage($width, 50, $background); $xaxis->setImageFormat('png'); $xaxis->drawImage($draw); $with_axes->addImage($combined); $with_axes->addImage($xaxis); $with_axes->resetIterator(); $output = $with_axes->appendImages(true); file_put_contents("{$TMP_PATH}/{$tmp_file}", $output); return array("img" => array("id" => $tmp_file, "yaxis" => "testest"), "div" => array("class" => "image-player", "xml" => "<div id='media'>" . "<div style='width:100px; margin: 0 auto;'>1367539200000000</div>" . "<div id='jet' class='colormap'></div>" . "<div class='range'><p class='lower'>-2</p><p class='upper'>2</p></div>" . "<div style='clear: both;'></div>" . "<div id='media-controls'>" . "<button id='play-pause-button' title='play' onclick='togglePlayPause();'>Play</button>" . "<button id='stop-button' title='stop' onclick='stopPlay();'>Stop</button>" . "<progress id='progress-bar' min='0' max='100' value='0' style='width:" . ($width - $width * 10 / 100) . "px'>0% played</progress>" . "</div>" . "</div>" . "<div id='timestamp1' style='display: none;' data='" . $start . "'></div>" . "<div id='timestamp2' style='display: none;' data='0'></div>")); }
public function text($text, $font, $size, $color = "#00000000", $locate = THINKIMAGE_WATER_SOUTHEAST, $offset = 0, $angle = 0) { if (empty($this->img)) { throw new Exception("没有可以被写入文字的图像资源"); } if (!is_file($font)) { throw new Exception("不存在的字体文件:{$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); } else { if (!is_string($color) || 0 !== strpos($color, "#")) { throw new Exception("错误的颜色值"); } } $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 THINKIMAGE_WATER_SOUTHEAST: $x += $this->info["width"] - $w; $y += $this->info["height"] - $h; break; case THINKIMAGE_WATER_SOUTHWEST: $y += $this->info["height"] - $h; break; case THINKIMAGE_WATER_NORTHWEST: break; case THINKIMAGE_WATER_NORTHEAST: $x += $this->info["width"] - $w; break; case THINKIMAGE_WATER_CENTER: $x += ($this->info["width"] - $w) / 2; $y += ($this->info["height"] - $h) / 2; break; case THINKIMAGE_WATER_SOUTH: $x += ($this->info["width"] - $w) / 2; $y += $this->info["height"] - $h; break; case THINKIMAGE_WATER_EAST: $x += $this->info["width"] - $w; $y += ($this->info["height"] - $h) / 2; break; case THINKIMAGE_WATER_NORTH: $x += ($this->info["width"] - $w) / 2; break; case THINKIMAGE_WATER_WEST: $y += ($this->info["height"] - $h) / 2; break; default: if (is_array($locate)) { $posy = $locate[1]; $posx = $locate[0]; $x += $posx; $y += $posy; } else { throw new Exception("不支持的文字位置类型"); } } if (is_array($offset)) { $offset = array_map("intval", $offset); $oy = $offset[1]; $ox = $offset[0]; } 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 build() { // Prepage image $this->_canvas = new Imagick(); $this->_canvas->newImage(self::WIDTH, self::HEIGHT, new ImagickPixel("white")); $color['line'] = new ImagickPixel("rgb(216, 76, 64)"); $color['text'] = new ImagickPixel("rgb(16, 35, 132)"); $color['karma'] = new ImagickPixel("rgb(116, 194, 98)"); $color['force'] = new ImagickPixel("rgb(37, 168, 255)"); $color['bottom_bg'] = new ImagickPixel("rgb(255, 244, 224)"); $color['bg'] = new ImagickPixel("white"); $color['neutral'] = new ImagickPixel("rgb(200, 200, 200)"); $color['habr'] = new ImagickPixel("rgb(83, 121, 139)"); // Prepare canvas for drawing main graph $draw = new ImagickDraw(); $draw->setStrokeAntialias(true); $draw->setStrokeWidth(2); // Prepare values for drawing main graph define('PADDING', 10); // Draw bottom bg define('TOP_SPACER', 10); $draw = new ImagickDraw(); $draw->setFillColor($color['bg']); $draw->setStrokeColor($color['habr']); $draw->polyline(array(array('x' => 0, 'y' => 0), array('x' => self::WIDTH - 1, 'y' => 0), array('x' => self::WIDTH - 1, 'y' => self::HEIGHT - 1), array('x' => 0, 'y' => self::HEIGHT - 1), array('x' => 0, 'y' => 0))); $this->_canvas->drawImage($draw); $draw->destroy(); // Draw texts $draw = new ImagickDraw(); $draw->setTextUnderColor($color['bg']); $draw->setTextAlignment(Imagick::ALIGN_CENTER); $draw->setTextAntialias(true); $draw->setFillColor($color['text']); $draw->setFont(realpath('stuff/arialbd.ttf')); $code = $this->_user; $draw->setFontSize(strlen($code) > 8 ? 10 : 11); if (strlen($code) > 10) { $code = substr($code, 0, 9) . '...'; } $draw->annotation(self::WIDTH / 2, self::HEIGHT - 9, $code); $draw->setFont(realpath('stuff/consola.ttf')); $draw->setFontSize(11); $draw->setFillColor($color['neutral']); $draw->annotation(self::WIDTH / 2, 15, "хаброметр"); $text = sprintf('%01.2f', $this->_extremums['karma_min']) . ' / ' . sprintf('%01.2f', $this->_extremums['karma_max']); $draw->setFontSize(9); $draw->setFillColor($color['karma']); $draw->annotation(self::WIDTH / 2, 55, $text); $text = sprintf('%01.2f', $this->_extremums['habraforce_min']) . ' / ' . sprintf('%01.2f', $this->_extremums['habraforce_max']); $draw->setFontSize(9); $draw->setFillColor($color['force']); $draw->annotation(self::WIDTH / 2, 95, $text); $draw->setTextUnderColor($color['karma']); $draw->setFillColor($color['bg']); $draw->setFontSize(14); $draw->setFont(realpath('stuff/consolab.ttf')); $draw->annotation(self::WIDTH / 2, 35, sprintf('%01.2f', $this->_karma)); $draw->setTextUnderColor($color['force']); $draw->setFillColor($color['bg']); $draw->annotation(self::WIDTH / 2, 75, sprintf('%01.2f', $this->_habraforce)); $this->_canvas->drawImage($draw); $draw->destroy(); return true; }
/** * (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); } }
$state = $s['result']; $patternWidth = $state['patternWidth']; // Create Imagick objects echo '<li>initialisiere</li>'; 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');
/** * @see wcf\system\image\adapter\IImageAdapter::drawText() */ public function drawText($string, $x, $y) { $draw = new \ImagickDraw(); $draw->setFillColor($this->color); $draw->setTextAntialias(true); // draw text $draw->annotation($x, $y, $string); $this->imagick->drawImage($draw); }
private static function __getImage($img, $type) { $client = new Client(Config::get('services.dropbox.token'), Config::get('services.dropbox.appName')); $fileSystem = new Filesystem(new DropboxAdapter($client, '/images/')); $biggerW = $biggerH = false; if ($img->width > $img->height) { $biggerW = true; } else { $biggerH = true; } $image = $w = $h = null; $public_path = public_path($img->path); //code minh //get image from dropbox if ($img->store == 'dropbox') { try { $file = $fileSystem->read($img->path); $public_path = $file; } catch (Exception $e) { return false; } } //end code if (in_array($type, ['with-logo', 'large-thumb'])) { if ($biggerW) { $w = 450; } else { $h = 450; } } else { if (in_array($type, ['thumb', 'small-thumb'])) { if ($type == 'thumb') { if ($biggerW) { $w = 150; } else { $h = 150; } } else { if ($biggerW) { $w = 100; } else { $h = 100; } } } else { if (in_array($type, ['crop', 'newcrop'])) { $h = 300; $w = 300; if ($type == 'newcrop') { $w = 600; } } } } try { if (in_array($type, ['crop', 'newcrop'])) { $image = Image::make($public_path)->fit($w, $h, function ($constraint) { $constraint->aspectRatio(); }); } else { $image = Image::make($public_path)->resize($w, $h, function ($constraint) { $constraint->aspectRatio(); }); } } catch (Exception $e) { return false; } if ($type == 'with-logo') { if (Cache::has('mask')) { $mask = Cache::get('mask'); } else { $mask = Configure::where('ckey', 'mask')->pluck('cvalue'); if (empty($mask)) { $mask = 'Visual Impact'; } Cache::forever('mask', $mask); } $size = 50; $w = $image->width(); $h = $image->height(); $x = round($w / 2); $y = round($h / 2); $img = Image::canvas($w, $h); $string = wordwrap($mask, 15, '|'); $strings = explode('|', $string); $line = 2; $i = round($y - count($strings) / 2 * ($size + $line)); $from = $i - 20; foreach ($strings as $string) { $draw = new \ImagickDraw(); $draw->setStrokeAntialias(true); $draw->setTextAntialias(true); $draw->setFont(public_path('assets' . DS . 'fonts' . DS . 'times.ttf')); $draw->setFontSize($size); $draw->setFillColor('rgb(0, 0, 0)'); $draw->setFillOpacity(0.2); $draw->setTextAlignment(\Imagick::ALIGN_CENTER); $draw->setStrokeColor('#fff'); $draw->setStrokeOpacity(0.2); $draw->setStrokeWidth(1); $dimensions = $img->getCore()->queryFontMetrics($draw, $string); $posy = $i + $dimensions['textHeight'] * 0.65 / 2; $img->getCore()->annotateImage($draw, $x, $posy, 0, $string); $i += $size + $line; } return $image->insert($img, 'center', $x, $y)->encode('jpg'); } if ($image) { return $image->encode('jpg'); } return false; }
public function build() { // Prepage image $this->_canvas = new Imagick(); $this->_canvas->newImage(self::WIDTH, self::HEIGHT, new ImagickPixel("white")); $color['line'] = new ImagickPixel("rgb(216, 76, 64)"); $color['text'] = new ImagickPixel("rgb(16, 35, 132)"); $color['karma'] = new ImagickPixel("rgb(116, 194, 98)"); $color['force'] = new ImagickPixel("rgb(37, 168, 255)"); $color['bottom_bg'] = new ImagickPixel("rgb(255, 244, 224)"); $color['bg'] = new ImagickPixel("white"); $color['neutral'] = new ImagickPixel("rgb(200, 200, 200)"); // Prepare canvas for drawing main graph $draw = new ImagickDraw(); $draw->setStrokeColor($color['line']); $draw->setFillColor($color['bg']); $draw->setStrokeAntialias(true); $draw->setStrokeWidth(2); // Prepare values for drawing main graph define('BOTTOM_PAD', 30); define('TOP_PAD', 25); define('LEFT_PAD', 43); define('RIGHT_PAD', 15); $graph = array('b' => self::HEIGHT - BOTTOM_PAD, 't' => TOP_PAD); $graph['height'] = $graph['b'] - $graph['t']; $dataHeight = $this->_max_karma - $this->_min_karma; if ($dataHeight != 0) { $graph['k'] = $graph['height'] / $dataHeight; } else { $graph['k'] = 1; } $karma = array_reverse($this->_karma); $graph['segmentWidth'] = (self::WIDTH - LEFT_PAD - RIGHT_PAD) / (count($karma) - 1); $lastX = LEFT_PAD; $lastY = $karma[0]; $graph['cords'] = array(); foreach ($karma as $y) { $graph['cords'][] = array('x' => (double) $lastX, 'y' => $graph['b'] - round($y - $this->_min_karma) * $graph['k']); $lastX += $graph['segmentWidth']; } //Draw graph $draw->polyline($graph['cords']); $this->_canvas->drawImage($draw); // Draw bottom bg define('TOP_SPACER', 10); $draw = new ImagickDraw(); $draw->setFillColor($color['bottom_bg']); $draw->polygon(array(array('x' => 0, 'y' => $graph['b'] + TOP_SPACER), array('x' => self::WIDTH, 'y' => $graph['b'] + TOP_SPACER), array('x' => self::WIDTH, 'y' => self::HEIGHT), array('x' => 0, 'y' => self::HEIGHT))); $this->_canvas->drawImage($draw); $draw->destroy(); // Draw texts $draw = new ImagickDraw(); $draw->setTextAntialias(true); $draw->setFontSize(12); $draw->setFillColor($color['text']); $draw->setFont(realpath('stuff/arial.ttf')); $draw->annotation(2, 13, 'Хаброметр юзера'); $draw->setFont(realpath('stuff/arialbd.ttf')); $code = $this->_user; if (strlen($code) > 25) { $code = substr($code, 0, 22) . '...'; } $draw->annotation(125, 13, $code); $image = new Imagick('stuff/bg-user2.gif'); $this->_canvas->compositeImage($image, Imagick::COMPOSITE_COPY, 109, 2, Imagick::CHANNEL_ALL); $image->clear(); $image->destroy(); $this->_canvas->drawImage($draw); $draw->destroy(); $draw = new ImagickDraw(); $draw->setFontSize(10); $draw->setFillColor($color['karma']); $draw->setFont(realpath('stuff/consola.ttf')); $draw->annotation(2, $graph['t'] + 5, sprintf('%01.2f', $this->_max_karma)); $draw->annotation(2, $graph['b'] + 2, sprintf('%01.2f', $this->_min_karma)); $draw->setFontSize(10); $draw->setFillColor($color['neutral']); $draw->setFont(realpath('stuff/consola.ttf')); $t = preg_split('/-|\\s|:/', $this->_logTime); $this->_canvas->annotateImage($draw, self::WIDTH - 3, $graph['b'] + 2, -90, $t[2] . '.' . $t[1] . '.' . substr($t[0], -2) . ' ' . $t[3] . ':' . $t[4]); $this->_canvas->drawImage($draw); $draw->destroy(); $draw = new ImagickDraw(); $draw->setFillColor($color['karma']); $text = 'min/max: ' . sprintf('%01.2f', $this->_extremums['karma_min']) . ' / ' . sprintf('%01.2f', $this->_extremums['karma_max']); $draw->setFontSize(12); $draw->setFont(realpath('stuff/consola.ttf')); $draw->setFillColor($color['bg']); $draw->annotation(3, $graph['b'] + 25, $text); $draw->setFillColor($color['karma']); $draw->annotation(2, $graph['b'] + 24, $text); $this->_canvas->drawImage($draw); $draw->destroy(); $draw = new ImagickDraw(); $draw->setTextAlignment(Imagick::ALIGN_RIGHT); $text = 'min/max: ' . sprintf('%01.2f', $this->_extremums['habraforce_min']) . ' / ' . sprintf('%01.2f', $this->_extremums['habraforce_max']); $draw->setFontSize(12); $draw->setFont(realpath('stuff/consola.ttf')); $draw->setFillColor($color['bg']); $draw->annotation(self::WIDTH - 3, $graph['b'] + 25, $text); $draw->setFillColor($color['force']); $draw->annotation(self::WIDTH - 2, $graph['b'] + 24, $text); $this->_canvas->drawImage($draw); $draw->destroy(); $draw = new ImagickDraw(); $draw->setTextAlignment(Imagick::ALIGN_RIGHT); $draw->setTextUnderColor($color['karma']); $draw->setFillColor($color['bg']); $draw->setFontSize(14); $draw->setFont(realpath('stuff/consolab.ttf')); $textInfo = $this->_canvas->queryFontMetrics($draw, sprintf('%01.2f', $this->_habraforce), null); $draw->annotation($lastX - $graph['segmentWidth'] + 1 - $textInfo['textWidth'] - 10, 13, sprintf('%01.2f', $karma[count($karma) - 1])); $draw->setTextUnderColor($color['force']); $draw->setFillColor($color['bg']); $draw->annotation($lastX - $graph['segmentWidth'] + 1, 13, sprintf('%01.2f', $this->_habraforce)); $this->_canvas->drawImage($draw); $draw->destroy(); $image = new Imagick('stuff/logo_mini.png'); $this->_canvas->compositeImage($image, Imagick::COMPOSITE_COPY, 3, 47, Imagick::CHANNEL_ALL); $image->clear(); $image->destroy(); return true; }
function setTextAntialias($fillColor, $backgroundColor) { $draw = new \ImagickDraw(); $draw->setStrokeColor('none'); $draw->setFillColor($fillColor); $draw->setStrokeWidth(1); $draw->setFontSize(32); $draw->setTextAntialias(false); $draw->annotation(5, 30, "Lorem Ipsum!"); $draw->setTextAntialias(true); $draw->annotation(5, 65, "Lorem Ipsum!"); $imagick = new \Imagick(); $imagick->newImage(220, 80, $backgroundColor); $imagick->setImageFormat("png"); $imagick->drawImage($draw); //Scale the image so that people can see the aliasing. $imagick->scaleImage(220 * 6, 80 * 6); $imagick->cropImage(640, 480, 0, 0); header("Content-Type: image/png"); echo $imagick->getImageBlob(); }
var_dump($draw->getGravity() === Imagick::GRAVITY_SOUTHEAST); // stroke $draw->setStrokeAntialias(false); var_dump($draw->getStrokeAntialias()); $draw->setStrokeColor(new ImagickPixel('#F02B88')); var_dump($draw->getStrokeColor()->getColor()); $draw->setStrokeDashArray(array(1, 2, 3)); var_dump($draw->getStrokeDashArray()); $draw->setStrokeDashOffset(-1); var_dump($draw->getStrokeDashOffset()); $draw->setStrokeLineCap(Imagick::LINECAP_SQUARE); var_dump($draw->getStrokeLineCap() === Imagick::LINECAP_SQUARE); $draw->setStrokeLineJoin(Imagick::LINEJOIN_BEVEL); var_dump($draw->getStrokeLineJoin() === Imagick::LINEJOIN_BEVEL); $draw->setStrokeMiterLimit(3); var_dump($draw->getStrokeMiterLimit()); $draw->setStrokeOpacity(0.9); printf("%.2f\n", $draw->getStrokeOpacity()); $draw->setStrokeWidth(1.2); printf("%.2f\n", $draw->getStrokeWidth()); // text $draw->setTextAlignment(Imagick::ALIGN_CENTER); var_dump($draw->getTextAlignment() === Imagick::ALIGN_CENTER); $draw->setTextAntialias(false); var_dump($draw->getTextAntialias()); $draw->setTextDecoration(Imagick::DECORATION_LINETROUGH); var_dump($draw->getTextDecoration() === Imagick::DECORATION_LINETROUGH); $draw->setTextEncoding('UTF-8'); var_dump($draw->getTextEncoding()); $draw->setTextUnderColor('cyan'); var_dump($draw->getTextUnderColor()->getColor());
/** * @see \wcf\system\image\adapter\IImageAdapter::drawText() */ public function drawText($text, $x, $y, $font, $size, $opacity = 1) { $draw = new \ImagickDraw(); $draw->setFillOpacity($opacity); $draw->setFillColor($this->color); $draw->setTextAntialias(true); $draw->setFont($font); $draw->setFontSize($size); // draw text $draw->annotation($x, $y, $text); if ($this->imagick->getImageFormat() == 'GIF') { $this->imagick = $this->imagick->coalesceImages(); do { $this->imagick->drawImage($draw); } while ($this->imagick->nextImage()); } else { $this->imagick->drawImage($draw); } }
/** * Get raw boxsize without any non-core features * * @param string $text * @return \Intervention\Image\Size */ protected function getCoreBoxSize($text = null) { $text = is_null($text) ? $this->text : $text; $imagick = new \Imagick(); $draw = new \ImagickDraw(); $draw->setStrokeAntialias(true); $draw->setTextAntialias(true); $draw->setFontSize($this->size); $draw->setFont($this->file); // get boxsize $size = $imagick->queryFontMetrics($draw, $text); return new Size($size['textWidth'], $size['textHeight']); }
/** * 在图片上添加验证文字 * @param resource $image 图片对象 * @param string $text 要添加的字符 * @return resource 图片对象 */ protected function imagickDrawText($image, $text) { $draw = new \ImagickDraw(); $draw->setFont($this->font); $draw->setFontSize($this->height * 0.8); $draw->setFillColor(new \ImagickPixel('#333333')); $draw->setStrokeAntialias(true); $draw->setTextAntialias(true); $metrics = $image->queryFontMetrics($draw, $text); $draw->annotation(0, $metrics['ascender'], $text); $image->drawImage($draw); $draw->destroy(); return $image; }
/** * {@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); $pixel->clear(); $pixel->destroy(); $text->clear(); $text->destroy(); } catch (\ImagickException $e) { throw new RuntimeException('Draw text operation failed', $e->getCode(), $e); } return $this; }
public function build() { // Prepage image $this->_canvas = new Imagick(); $this->_canvas->newImage(self::WIDTH, self::HEIGHT, new ImagickPixel("white")); $color['line'] = new ImagickPixel("rgb(216, 76, 64)"); $color['text'] = new ImagickPixel("rgb(16, 35, 132)"); $color['karma'] = new ImagickPixel("rgb(116, 194, 98)"); $color['force'] = new ImagickPixel("rgb(37, 168, 255)"); $color['bottom_bg'] = new ImagickPixel("rgb(255, 244, 224)"); $color['bg'] = new ImagickPixel("white"); $color['neutral'] = new ImagickPixel("rgb(200, 200, 200)"); $color['habr'] = new ImagickPixel("rgb(83, 121, 139)"); // Prepare canvas for drawing main graph $draw = new ImagickDraw(); $draw->setStrokeAntialias(true); $draw->setStrokeWidth(2); // Prepare values for drawing main graph define('PADDING', 10); // Draw bottom bg define('TOP_SPACER', 10); $draw = new ImagickDraw(); $draw->setFillColor($color['bg']); $draw->setStrokeColor($color['habr']); $draw->polyline(array(array('x' => 0, 'y' => 0), array('x' => self::WIDTH - 1, 'y' => 0), array('x' => self::WIDTH - 1, 'y' => self::HEIGHT - 1), array('x' => 0, 'y' => self::HEIGHT - 1), array('x' => 0, 'y' => 0))); $this->_canvas->drawImage($draw); $draw->destroy(); // Draw texts $draw = new ImagickDraw(); $draw->setTextUnderColor($color['bg']); $draw->setTextAntialias(true); $draw->setFillColor($color['text']); $draw->setFont(realpath('stuff/arialbd.ttf')); $code = $this->_user; $draw->setFontSize(strlen($code) > 8 ? 10 : 11); if (strlen($code) > 10) { $code = substr($code, 0, 9) . '...'; } $draw->annotation(80, 13, $code); $textInfo = $this->_canvas->queryFontMetrics($draw, $code, null); $nextX = 80 + 9 + $textInfo['textWidth']; $draw->setFont(realpath('stuff/consola.ttf')); $draw->setFontSize(11); $draw->setFillColor($color['neutral']); $draw->annotation(5, 13, "хаброметр"); $draw->setTextUnderColor($color['karma']); $draw->setFillColor($color['bg']); $draw->setFontSize(12); $draw->setFont(realpath('stuff/consolab.ttf')); $draw->annotation($nextX, 13, $text = sprintf('%01.2f', $this->_karma)); $textInfo = $this->_canvas->queryFontMetrics($draw, $text, null); $nextX += $textInfo['textWidth'] + 4; $draw->setTextUnderColor($color['bg']); $draw->setFont(realpath('stuff/arialbd.ttf')); $text = sprintf('%01.2f', $this->_extremums['karma_min']) . '/' . sprintf('%01.2f', $this->_extremums['karma_max']); $draw->setFontSize(8); $draw->setFillColor($color['karma']); $draw->annotation($nextX, 13, $text); $textInfo = $this->_canvas->queryFontMetrics($draw, $text, null); $nextX += $textInfo['textWidth'] + 9; $draw->setFontSize(12); $draw->setFont(realpath('stuff/consolab.ttf')); $draw->setTextUnderColor($color['force']); $draw->setFillColor($color['bg']); $draw->annotation($nextX, 13, $text = sprintf('%01.2f', $this->_habraforce)); $textInfo = $this->_canvas->queryFontMetrics($draw, $text, null); $nextX += $textInfo['textWidth'] + 4; $draw->setTextUnderColor($color['bg']); $draw->setFont(realpath('stuff/arialbd.ttf')); $text = sprintf('%01.2f', $this->_extremums['habraforce_min']) . '/' . sprintf('%01.2f', $this->_extremums['habraforce_max']); $draw->setFontSize(8); $draw->setFillColor($color['force']); $draw->annotation($nextX, 13, $text); $image = new Imagick('stuff/bg-user2.gif'); $this->_canvas->compositeImage($image, Imagick::COMPOSITE_COPY, 64, 3, Imagick::CHANNEL_ALL); $image->clear(); $image->destroy(); $this->_canvas->drawImage($draw); $draw->destroy(); return true; }
function create_thumbnail($filename, $save2disk = true, $resize_type = 0) { $filename = $this->basename($filename); if ($this->is_image($this->mmhclass->info->root_path . $this->mmhclass->info->config['upload_path'] . $filename) == true) { $extension = $this->file_extension($filename); $thumbnail = $this->thumbnail_name($filename); if ($save2disk == true) { // Seemed easier to build the image resize upload // option into the already established thumbnail function // instead of waisting time trying to chop it up for new one. if ($resize_type > 0 && $resize_type <= 8) { $thumbnail = $filename; $this->mmhclass->info->config['advanced_thumbnails'] = false; $size_values = array(1 => array("w" => 100, "h" => 75), 2 => array("w" => 150, "h" => 112), 3 => array("w" => 320, "h" => 240), 4 => array("w" => 640, "h" => 480), 5 => array("w" => 800, "h" => 600), 6 => array("w" => 1024, "h" => 768), 7 => array("w" => 1280, "h" => 1024), 8 => array("w" => 1600, "h" => 1200)); $thumbnail_size = $size_values[$resize_type]; } else { $thumbnail_size = $this->scale($filename, $this->mmhclass->info->config['thumbnail_width'], $this->mmhclass->info->config['thumbnail_height']); } if ($this->manipulator == "imagick") { // New Design of Advanced Thumbnails created by: IcyTexx - http://www.hostili.com // Classic Design of Advanced Thumbnails created by: Mihalism Technologies - http://www.mihalism.net $canvas = new Imagick(); $athumbnail = new Imagick(); $imagick_version = $canvas->getVersion(); // Imagick needs to start giving real version number, not build number. $new_thumbnails = version_compare($imagick_version['versionNumber'], "1621", ">=") == true ? true : false; $athumbnail->readImage("{$this->mmhclass->info->root_path}{$this->mmhclass->info->config['upload_path']}{$filename}[0]"); $athumbnail->flattenImages(); $athumbnail->orgImageHeight = $athumbnail->getImageHeight(); $athumbnail->orgImageWidth = $athumbnail->getImageWidth(); $athumbnail->orgImageSize = $athumbnail->getImageLength(); $athumbnail->thumbnailImage($thumbnail_size['w'], $thumbnail_size['h']); if ($this->mmhclass->info->config['advanced_thumbnails'] == true) { $thumbnail_filesize = $this->format_filesize($athumbnail->orgImageSize, true); $resobar_filesize = $thumbnail_filesize['f'] < 0 || $thumbnail_filesize['c'] > 9 ? $this->mmhclass->lang['5454'] : sprintf("%s%s", round($thumbnail_filesize['f']), $this->mmhclass->lang['7071'][$thumbnail_filesize['c']]); if ($new_thumbnails == true) { $textdraw = new ImagickDraw(); $textdrawborder = new ImagickDraw(); if ($athumbnail->getImageWidth() > 113) { $textdraw->setFillColor(new ImagickPixel("white")); $textdraw->setFontSize(9); $textdraw->setFont("{$mmhclass->info->root_path}css/fonts/sf_fedora_titles.ttf"); $textdraw->setFontWeight(900); $textdraw->setGravity(8); $textdraw->setTextKerning(1); $textdraw->setTextAntialias(false); $textdrawborder->setFillColor(new ImagickPixel("black")); $textdrawborder->setFontSize(9); $textdrawborder->setFont("{$mmhclass->info->root_path}css/fonts/sf_fedora_titles.ttf"); $textdrawborder->setFontWeight(900); $textdrawborder->setGravity(8); $textdrawborder->setTextKerning(1); $textdrawborder->setTextAntialias(false); $array_x = array("-1", "0", "1", "1", "1", "0", "-1", "-1"); $array_y = array("-1", "-1", "-1", "0", "1", "1", "1", "0"); foreach ($array_x as $key => $value) { $athumbnail->annotateImage($textdrawborder, $value, 3 - $array_y[$key], 0, "{$athumbnail->orgImageWidth}x{$athumbnail->orgImageHeight} - {$resobar_filesize}"); } $athumbnail->annotateImage($textdraw, 0, 3, 0, "{}x{$athumbnail->orgImageHeight} - {$resobar_filesize}"); } } else { $transback = new Imagick(); $canvasdraw = new ImagickDraw(); $canvas->newImage($athumbnail->getImageWidth(), $athumbnail->getImageHeight() + 12, new ImagickPixel("black")); $transback->newImage($canvas->getImageWidth(), $canvas->getImageHeight() - 12, new ImagickPixel("white")); $canvas->compositeImage($transback, 40, 0, 0); $canvasdraw->setFillColor(new ImagickPixel("white")); $canvasdraw->setGravity(8); $canvasdraw->setFontSize(10); $canvasdraw->setFontWeight(900); $canvasdraw->setFont("AvantGarde-Demi"); $canvas->annotateImage($canvasdraw, 0, 0, 0, "{$athumbnail->orgImageWidth}x{$athumbnail->orgImageHeight} - {$resobar_filesize}"); $canvas->compositeImage($athumbnail, 40, 0, 0); $athumbnail = $canvas->clone(); } } if ($this->mmhclass->info->config['thumbnail_type'] == "jpeg") { $athumbnail->setImageFormat("jpeg"); $athumbnail->setImageCompression(9); } else { $athumbnail->setImageFormat("png"); } $athumbnail->writeImage($this->mmhclass->info->root_path . $this->mmhclass->info->config['upload_path'] . $thumbnail); } else { // I hate GD. Piece of crap supports nothing. NOTHING! if (in_array($extension, array("png", "gif", "jpg", "jpeg")) == true) { $function_extension = str_replace("jpg", "jpeg", $extension); $image_function = "imagecreatefrom{$function_extension}"; $image = $image_function($this->mmhclass->info->root_path . $this->mmhclass->info->config['upload_path'] . $filename); $imageinfo = $this->get_image_info($this->mmhclass->info->root_path . $this->mmhclass->info->config['upload_path'] . $this->basename($filename)); $thumbnail_image = imagecreatetruecolor($thumbnail_size['w'], $thumbnail_size['h']); $index = imagecolortransparent($thumbnail_image); if ($index < 0) { $white = imagecolorallocate($thumbnail_image, 255, 255, 255); imagefill($thumbnail_image, 0, 0, $white); } imagecopyresampled($thumbnail_image, $image, 0, 0, 0, 0, $thumbnail_size['w'], $thumbnail_size['h'], $imageinfo['width'], $imageinfo['height']); $image_savefunction = sprintf("image%s", $this->mmhclass->info->config['thumbnail_type'] == "jpeg" ? "jpeg" : "png"); $image_savefunction($thumbnail_image, $this->mmhclass->info->root_path . $this->mmhclass->info->config['upload_path'] . $thumbnail); chmod($this->mmhclass->info->root_path . $this->mmhclass->info->config['upload_path'] . $thumbnail, 0644); imagedestroy($image); imagedestroy($thumbnail_image); } else { trigger_error("Image format not supported by GD", E_USER_ERROR); } } chmod($this->mmhclass->info->root_path . $this->mmhclass->info->config['upload_path'] . $thumbnail, 0644); } else { readfile($this->mmhclass->info->root_path . $this->mmhclass->info->config['upload_path'] . $thumbnail); } } }
/** * 图像添加文字 * @param string $text 添加的文字 * @param string $font 字体路径 * @param integer $size 字号 * @param string $color 文字颜色 * @param integer $locate 文字写入位置 * @param integer $offset 文字相对当前位置的偏移量 * @param integer $angle 文字倾斜角度 */ public function text($text, $font, $size, $color = '#00000000', $locate = Image::IMAGE_WATER_SOUTHEAST, $offset = 0, $angle = 0) { //资源检测 if (empty($this->img)) { throw new Exception('没有可以被写入文字的图像资源'); } if (!is_file($font)) { throw new Exception("不存在的字体文件:{$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('错误的颜色值'); } $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('不支持的文字位置类型'); } } /* 设置偏移量 */ 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 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; } }