function IMAGEN_tipo_normal() { $escalado = 'IMG/i/m/' . $_GET['ancho'] . '_' . $_GET['alto'] . '_' . $_GET['sha1']; $origen = 'IMG/i/' . $_GET['sha1']; $ancho = $_GET['ancho']; $alto = $_GET['alto']; if (@($ancho * $alto) > 562500) { die('La imagen solicitada excede el límite de este servicio'); } if (!file_exists($escalado)) { $im = new Imagick($origen); $im->setCompression(Imagick::COMPRESSION_JPEG); $im->setCompressionQuality(85); $im->setImageFormat('jpeg'); $im->stripImage(); $im->despeckleImage(); $im->sharpenImage(0.5, 1); //$im->reduceNoiseImage(0); $im->setInterlaceScheme(Imagick::INTERLACE_PLANE); $im->resizeImage($ancho, $alto, imagick::FILTER_LANCZOS, 1); $im->writeImage($escalado); $im->destroy(); } $im = new Imagick($escalado); $output = $im->getimageblob(); $outputtype = $im->getFormat(); $im->destroy(); header("Content-type: {$outputtype}"); header("Content-length: " . filesize($escalado)); echo $output; }
public function pdfAction() { $model = $this->_processSvg(); $scale = $this->getRequest()->getPost('print_scale'); $model->addWhiteFontForPDF(); $data = $model->normalizeSvgData(); if ($model->getAdditionalData('order_increment_id')) { $filename = 'Order_' . $model->getAdditionalData('order_increment_id') . '_Image.pdf'; } else { $filename = 'Customer_Product_Image.pdf'; } $this->getResponse()->setHttpResponseCode(200)->setHeader('Pragma', 'public', true)->setHeader('Content-type', 'application/pdf', true)->setHeader('Content-Disposition', 'attachment; filename="' . $filename . '"', true); $this->getResponse()->clearBody(); //$this->getResponse()->setBody(str_replace('xlink:','',$data)); $imagick = new Imagick(); $imagick->readImageBlob($data); if ($scale != 1 && $scale <= 15) { $imagick->scaleImage($scale * $imagick->getImageWidth(), $scale * $imagick->getImageHeight()); } $imagick->setImageFormat("pdf"); /*$imagick->writeImage(MAGENTO_ROOT.'/media/us-map.pdf');scaleImage */ $this->getResponse()->setBody($imagick); $imagick->clear(); $imagick->destroy(); }
/** * 保存图像 * @param string $imgname 图像保存名称 * @param string $type 图像类型 * @param boolean $interlace 是否对JPEG类型图像设置隔行扫描 * @throws \Exception */ public function save($imgname, $type = NULL, $interlace = true) { if (empty($this->img)) { throw new \Exception(_('No image resources can be saved')); } //设置图片类型 if (is_null($type)) { $type = $this->info['type']; } else { $type = strtolower($type); $this->img->setImageFormat($type); } //JPEG图像设置隔行扫描 if ('jpeg' == $type || 'jpg' == $type) { $this->img->setImageInterlaceScheme(1); } //去除图像配置信息 $this->img->stripImage(); //保存图像 $imgname = realpath(dirname($imgname)) . '/' . basename($imgname); //强制绝对路径 if ('gif' == $type) { $this->img->writeImages($imgname, true); } else { $this->img->writeImage($imgname); } }
function save($file_name = null, $quality = null) { $type = $this->out_type; if (!$type) { $type = $this->img_type; } if (!self::supportSaveType($type)) { throw new lmbImageTypeNotSupportedException($type); } $this->img->setImageFormat($type); $this->img->setImageFilename($file_name); if (!is_null($quality) && strtolower($type) == 'jpeg') { if (method_exists($this->img, 'setImageCompression')) { $this->img->setImageCompression(imagick::COMPRESSION_JPEG); $this->img->setImageCompressionQuality($quality); } else { $this->img->setCompression(imagick::COMPRESSION_JPEG); $this->img->setCompressionQuality($quality); } } if (!$this->img->writeImage($file_name)) { throw new lmbImageSaveFailedException($file_name); } $this->destroyImage(); }
/** * @param $path */ public function save($path, $format = null, $quality = null) { if (!$format) { $format = "png"; } $this->resource->stripimage(); $this->resource->setImageFormat($format); if ($quality) { $this->resource->setCompressionQuality((int) $quality); $this->resource->setImageCompressionQuality((int) $quality); } $this->resource->writeImage($path); return $this; }
public function assignMimeType(Imagick $target) { if ($this->mimeType == 'image/jpeg') { $target->setImageFormat('jpg'); } else { if ($this->mimeType == 'image/gif') { $target->setImageFormat('gif'); } else { if ($this->mimeType == 'image/png') { $target->setImageFormat('png'); } } } }
/** * {@inheritDoc} */ public function apply($absolutePath) { $info = pathinfo($absolutePath); if (isset($info['extension']) && false !== strpos(strtolower($info['extension']), 'pdf')) { // If it doesn't exists, extract the first page of the PDF if (!file_exists("{$absolutePath}.png")) { $this->imagick->readImage($absolutePath . '[0]'); $this->imagick->setImageFormat('png'); $this->imagick->writeImage("{$absolutePath}.png"); $this->imagick->clear(); } $absolutePath .= '.png'; } return $absolutePath; }
protected function _save_function($extension, &$quality) { switch (strtolower($extension)) { case 'jpg': case 'jpeg': $type = IMAGETYPE_JPEG; if ($this->type == "png" || $this->type == "gif") { $this->im->borderImage(new ImagickPixel("white"), 1, 1); } $this->im->setImageFormat('jpeg'); break; case 'gif': $type = IMAGETYPE_GIF; $this->im->setImageFormat('gif'); break; case 'png': $type = IMAGETYPE_PNG; $this->im->setImageFormat('png'); break; default: throw new waException(_ws(sprintf('Installed ImageMagick does not support %s images', $extension))); break; } $quality = $quality - 5; return $type; }
/** * Tries to converts the <b>$input</b> image into the <b>$output</b> format. * * @param string $input The input file. * @param string $output The output file. * @return void */ public static function convert($input, $output) { $inputType = strtolower(pathinfo($input, PATHINFO_EXTENSION)); $outputType = strtolower(pathinfo($output, PATHINFO_EXTENSION)); // Check for output file without extension and reuse input type if ($outputType === '') { $outputType = $inputType; $output .= ".{$outputType}"; } if ($inputType === 'svg') { self::prepareSvg($input); } if ($inputType === $outputType) { file_put_contents($output, file_get_contents($input)); } elseif (extension_loaded('imagick') === true) { $imagick = new \Imagick($input); $imagick->setImageFormat($outputType); $imagick->writeImage($output); // The following code is not testable when imagick is installed // @codeCoverageIgnoreStart } elseif (self::hasImagickConvert() === true) { $input = escapeshellarg($input); $output = escapeshellarg($output); system("convert {$input} {$output}"); } else { $fallback = substr($output, 0, -strlen($outputType)) . $inputType; echo "WARNING: Cannot generate image of type '{$outputType}'. This", " feature needs either the\n pecl/imagick extension or", " the ImageMagick cli tool 'convert'.\n\n", "Writing alternative image:\n{$fallback}\n\n"; file_put_contents($fallback, file_get_contents($input)); } // @codeCoverageIgnoreEnd }
function alfath_svg_compiler($options) { global $wp_filesystem; if (!class_exists('Imagick')) { return new WP_Error('class_not_exist', 'Your server not support imagemagick'); } $im = new Imagick(); $im->setBackgroundColor(new ImagickPixel('transparent')); if (empty($wp_filesystem)) { require_once ABSPATH . '/wp-admin/includes/file.php'; WP_Filesystem(); } $file = get_template_directory() . '/assets/img/nav.svg'; $target = get_template_directory() . '/assets/img/nav-bg.png'; if ($wp_filesystem->exists($file)) { //check for existence $svg = $wp_filesystem->get_contents($file); if (!$svg) { return new WP_Error('reading_error', 'Error when reading file'); } //return error object $svg = preg_replace('/fill="#([0-9a-f]{6})"/', 'fill="' . $options['secondary-color'] . '"', $svg); $im->readImageBlob($svg); $im->setImageFormat("png24"); $im->writeImage($target); $im->clear(); $im->destroy(); } else { return new WP_Error('not_found', 'File not found'); } }
function create_thumb($source_file, $thumb_file, $edge = THUMBNAIL_CROP_EDGE, &$src_w = NULL, &$src_h = NULL) { $composite_img = new Imagick($source_file); $blank_img = new Imagick(); $src_w = $composite_img->getImageWidth(); $src_h = $composite_img->getImageHeight(); if ($src_h > $edge && $src_w > $edge) { $composite_img->cropThumbnailImage($edge, $edge); $composite_img->setImageFormat('jpeg'); $composite_img->writeImage($thumb_file); $composite_img->clear(); $blank_img = $composite_img; } else { $blank_img->newImage($edge, $edge, new ImagickPixel('#DEF'), "jpg"); if ($src_w > $src_h) { $crop_x = $src_w / 2 - $edge / 2; $crop_y = 0; $offset_x = 0; $offset_y = $edge / 2 - $src_h / 2; } else { $crop_x = 0; $crop_y = $src_h / 2 - $edge / 2; $offset_x = $edge / 2 - $src_w / 2; $offset_y = 0; } $composite_img->cropImage($edge, $edge, $crop_x, $crop_y); $blank_img->compositeImage($composite_img, Imagick::COMPOSITE_OVER, $offset_x, $offset_y); $blank_img->setImageFormat('jpeg'); $blank_img->writeImage($thumb_file); $blank_img->clear(); } return $blank_img; }
/** * {@inheritDoc} */ public function getThumbnail($path, $maxX, $maxY, $scalingup, $fileview) { try { $svg = new \Imagick(); $svg->setBackgroundColor(new \ImagickPixel('transparent')); $content = stream_get_contents($fileview->fopen($path, 'r')); if (substr($content, 0, 5) !== '<?xml') { $content = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>' . $content; } // Do not parse SVG files with references if (stripos($content, 'xlink:href') !== false) { return false; } $svg->readImageBlob($content); $svg->setImageFormat('png32'); } catch (\Exception $e) { \OCP\Util::writeLog('core', $e->getmessage(), \OCP\Util::ERROR); return false; } //new image object $image = new \OC_Image(); $image->loadFromData($svg); //check if image object is valid if ($image->valid()) { $image->scaleDownToFit($maxX, $maxY); return $image; } return false; }
/** * Displays image without saving and lose changes * * This method adds the Content-type HTTP header * * @param string type (JPG,PNG...); * @param int quality 75 * * @return bool|PEAR_Error TRUE or a PEAR_Error object on error * @access public */ function display($type = '', $quality = null) { $options = is_array($quality) ? $quality : array(); if (is_numeric($quality)) { $options['quality'] = $quality; } $quality = $this->_getOption('quality', $options, 75); $this->imagick->setImageCompression($quality); if ($type && strcasecmp($type, $this->type)) { try { $this->imagick->setImageFormat($type); } catch (ImagickException $e) { return $this->raiseError('Could not save image to file (conversion failed).', IMAGE_TRANSFORM_ERROR_FAILED); } } try { $image = $this->imagick->getImageBlob(); } catch (ImagickException $e) { return $this->raiseError('Could not display image.', IMAGE_TRANSFORM_ERROR_IO); } header('Content-type: ' . $this->getMimeType($type)); echo $image; $this->free(); return true; }
/** * @param array $options * @param string $path */ private function prepareOutput(array $options, $path = null) { if (isset($options['format'])) { $this->imagick->setImageFormat($options['format']); } if (isset($options['animated']) && true === $options['animated']) { $format = isset($options['format']) ? $options['format'] : 'gif'; $delay = isset($options['animated.delay']) ? $options['animated.delay'] : null; $loops = 0; if (isset($options['animated.loops'])) { $loops = $options['animated.loops']; } else { // Calculating animated GIF iterations is a crap-shoot: https://www.imagemagick.org/discourse-server/viewtopic.php?f=1&t=23276 // Looks like it started working around 6.8.8-3: http://git.imagemagick.org/repos/ImageMagick/blob/a01518e08c840577cabd7d3ff291a9ba735f7276/ChangeLog#L914-916 $versionInfo = $this->imagick->getVersion(); if (isset($versionInfo['versionString'])) { preg_match('/ImageMagick ([0-9]+\\.[0-9]+\\.[0-9]+-[0-9])/', $versionInfo['versionString'], $versionInfo); if (isset($versionInfo[1])) { if (version_compare($versionInfo[1], '6.8.8-3', '>=')) { $loops = $this->imagick->getImageIterations(); } } } } $options['flatten'] = false; $this->layers->animate($format, $delay, $loops); } else { $this->layers->merge(); } $this->applyImageOptions($this->imagick, $options, $path); // flatten only if image has multiple layers if ((!isset($options['flatten']) || $options['flatten'] === true) && count($this->layers) > 1) { $this->flatten(); } }
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; }
public function getThumbnail($path, $maxX, $maxY, $scalingup, $fileview) { $mimetype = $fileview->getMimeType($path); $path = \OC_Helper::mimetypeIcon($mimetype); $path = \OC::$SERVERROOT . substr($path, strlen(\OC::$WEBROOT)); $svgPath = substr_replace($path, 'svg', -3); if (extension_loaded('imagick') && file_exists($svgPath) && count(@\Imagick::queryFormats("SVG")) === 1) { // http://www.php.net/manual/de/imagick.setresolution.php#85284 $svg = new \Imagick(); $svg->readImage($svgPath); $res = $svg->getImageResolution(); $x_ratio = $res['x'] / $svg->getImageWidth(); $y_ratio = $res['y'] / $svg->getImageHeight(); $svg->removeImage(); $svg->setResolution($maxX * $x_ratio, $maxY * $y_ratio); $svg->setBackgroundColor(new \ImagickPixel('transparent')); $svg->readImage($svgPath); $svg->setImageFormat('png32'); $image = new \OC_Image(); $image->loadFromData($svg); } else { $image = new \OC_Image($path); } return $image; }
function upload_image($arr_image, $location, $compression = null, $width = 245, $height = 170) { $image_location = ""; $allowedExts = array("gif", "jpeg", "jpg", "png", "JPG", "JPEG", "GIF", "PNG", "pdf", "PDF"); $temp = explode(".", $arr_image["file"]["name"]); $extension = end($temp); if (($arr_image["file"]["type"] == "image/gif" || $arr_image["file"]["type"] == "image/jpeg" || $arr_image["file"]["type"] == "image/jpg" || $arr_image["file"]["type"] == "image/pjpeg" || $arr_image["file"]["type"] == "image/x-png" || $arr_image["file"]["type"] == "image/png") && $arr_image["file"]["size"] < 1024 * 1000 * 10 && in_array($extension, $allowedExts)) { if ($arr_image["file"]["error"] > 0) { echo "Return Code: " . $arr_image["file"]["error"] . "<br>"; } else { $compression_type = Imagick::COMPRESSION_JPEG; $image_location = $location . "." . $extension; if (move_uploaded_file($arr_image["file"]["tmp_name"], $image_location)) { //echo "Image Uploaded to : ".$image_location; } else { //echo "Image not uploaded"; } if (is_null($compression)) { $im = new Imagick($image_location); $im->setImageFormat('jpg'); $im->setImageCompression($compression_type); $im->setImageCompressionQuality(95); $im->stripImage(); $im->thumbnailImage($width, $height); $image_location = $location . ".jpg"; $im->writeImage($image_location); } } } return $image_location; }
/** * @param Thumbnail $thumbnail * @return void * @throws Exception\NoThumbnailAvailableException */ public function refresh(Thumbnail $thumbnail) { try { $filenameWithoutExtension = pathinfo($thumbnail->getOriginalAsset()->getResource()->getFilename(), PATHINFO_FILENAME); $temporaryLocalCopyFilename = $thumbnail->getOriginalAsset()->getResource()->createTemporaryLocalCopy(); $documentFile = sprintf(in_array($thumbnail->getOriginalAsset()->getResource()->getFileExtension(), $this->getOption('paginableDocuments')) ? '%s[0]' : '%s', $temporaryLocalCopyFilename); $width = $thumbnail->getConfigurationValue('width') ?: $thumbnail->getConfigurationValue('maximumWidth'); $height = $thumbnail->getConfigurationValue('height') ?: $thumbnail->getConfigurationValue('maximumHeight'); $im = new \Imagick(); $im->setResolution($this->getOption('resolution'), $this->getOption('resolution')); $im->readImage($documentFile); $im->setImageFormat('png'); $im->setImageBackgroundColor('white'); $im->setImageCompose(\Imagick::COMPOSITE_OVER); $im->setImageAlphaChannel(\Imagick::ALPHACHANNEL_RESET); $im->thumbnailImage($width, $height, true); $im->flattenImages(); // Replace flattenImages in imagick 3.3.0 // @see https://pecl.php.net/package/imagick/3.3.0RC2 // $im->mergeImageLayers(\Imagick::LAYERMETHOD_MERGE); $resource = $this->resourceManager->importResourceFromContent($im->getImageBlob(), $filenameWithoutExtension . '.png'); $im->destroy(); $thumbnail->setResource($resource); $thumbnail->setWidth($width); $thumbnail->setHeight($height); } catch (\Exception $exception) { $filename = $thumbnail->getOriginalAsset()->getResource()->getFilename(); $sha1 = $thumbnail->getOriginalAsset()->getResource()->getSha1(); $message = sprintf('Unable to generate thumbnail for the given document (filename: %s, SHA1: %s)', $filename, $sha1); throw new Exception\NoThumbnailAvailableException($message, 1433109652, $exception); } }
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 = Escpos::IMG_DEFAULT; $this->printer->bitImage($escposImage, $size); }
/** * Create a new empty (1 x 1 px) gd true colour image * * @param integer Image width * @param integer Image Height */ public function create($x = 1, $y = 1) { $image = new Imagick(); $image->newImage($x, $y, new ImagickPixel('white')); $image->setImageFormat('png'); $this->setHolder($image); }
/** * 生成验证码 * @param string $file 图片保存文件名,不指定则图片会被直接输出 * @return null */ public function get($file = "") { $support = $this->support(); list($code, $answer) = $this->generateCode(); $image = null; @session_start(); $_SESSION['vitex.captcha.answer'] = strtolower($answer); if ($support == 'imagick') { $image = new \Imagick(); $image->newImage($this->width, $this->height, "none"); $image->setImageFormat('png'); $image = $this->imagickLine($image, $this->linenum); $image = $this->imagickDrawText($image, $code); $image->swirlImage(30); $image->oilPaintImage(1); if ($file) { $image->writeImage($file); } else { header("Content-type:image/png"); echo $image->getImageBlob(); } } else { $image = imagecreate($this->width, $this->height); $color = imagecolorallocate($image, 255, 255, 255); imagecolortransparent($image, $color); $this->gdLine($image, $this->linenum); $this->gdDrawText($image, $code); if ($file) { imagepng($image, $file); } else { header("Content-type: image/jpeg; Cache-Control: no-store, no-cache, must-revalidate"); imagepng($image); } } }
function create_mask($image_path_1, $image_path_2, $mask_path, $step_width, $step_height) { $info = new Imagick($image_path_1); $mask = new Imagick(); $mask->newImage($info->width, $info->height, 'none'); $mask->setImageFormat('png'); $chunk = new Imagick(); $chunk->newImage($step_width, $step_height, new ImagickPixel('black')); $chunk->setImageFormat('png'); $prefix1 = basename($image_path_1, '.png'); $prefix2 = basename($image_path_2, '.png'); $paths = glob("process/{$prefix1}*.png"); foreach ($paths as $path) { $path2 = "process/" . $prefix2 . substr(basename($path), strlen($prefix2)); // compare 1 and 2 $a = new Imagick($path); $b = new Imagick($path2); $diff = $a->compareImages($b, Imagick::METRIC_MEANSQUAREERROR); if ($diff[1] > 0) { preg_match('~.*?(\\d+)\\-(\\d+).png~', $path, $m) or die("Issue fetching the x y from {$path}\r\n"); $mask->compositeImage($chunk, Imagick::COMPOSITE_DEFAULT, $m[1], $m[2]); } } $mask->writeImage($mask_path); }
/** * Applies the effect. */ public function apply() { if (!method_exists($this->_image->imagick, 'polaroidImage') || !method_exists($this->_image->imagick, 'trimImage')) { throw new Horde_Image_Exception('Your version of Imagick is not compiled against a recent enough ImageMagick library to use the PolaroidImage effect.'); } try { // This determines the color of the underlying shadow. $this->_image->imagick->setImageBackgroundColor(new ImagickPixel($this->_params['shadowcolor'])); $this->_image->imagick->polaroidImage(new ImagickDraw(), $this->_params['angle']); // We need to create a new image to composite the polaroid over. // (yes, even if it's a transparent background evidently) $size = $this->_image->getDimensions(); $imk = new Imagick(); $imk->newImage($size['width'], $size['height'], $this->_params['background']); $imk->setImageFormat($this->_image->getType()); $result = $imk->compositeImage($this->_image->imagick, Imagick::COMPOSITE_OVER, 0, 0); $this->_image->imagick->clear(); $this->_image->imagick->addImage($imk); } catch (ImagickPixelException $e) { throw new Horde_Image_Exception($e); } catch (ImagickDrawException $e) { throw new Horde_Image_Exception($e); } catch (ImagickException $e) { throw new Horde_Image_Exception($e); } $imk->destroy(); }
public function renderImage() { //Create a ImagickDraw object to draw into. $draw = new \ImagickDraw(); $darkColor = new \ImagickPixel('brown'); //http://www.imagemagick.org/Usage/compose/#compose_terms $draw->setStrokeColor($darkColor); $draw->setFillColor('white'); $draw->setStrokeWidth(2); $draw->setFontSize(72); $draw->setStrokeOpacity(1); $draw->setStrokeColor($darkColor); $draw->setStrokeWidth(2); $draw->setFont("../fonts/CANDY.TTF"); $draw->setFontSize(140); $draw->setFillColor('none'); $draw->rectangle(0, 0, 1000, 300); $draw->setFillColor('white'); $draw->annotation(50, 180, "Lorem Ipsum!"); $imagick = new \Imagick(realpath("images/TestImage.jpg")); $draw->composite(\Imagick::COMPOSITE_MULTIPLY, -500, -200, 2000, 600, $imagick); //Create an image object which the draw commands can be rendered into $imagick = new \Imagick(); $imagick->newImage(1000, 300, "SteelBlue2"); $imagick->setImageFormat("png"); //Render the draw commands in the ImagickDraw object //into the image. $imagick->drawImage($draw); //Send the image to the browser header("Content-Type: image/png"); echo $imagick->getImageBlob(); }
/** * アバター自動生成処理 * * @param Model $model ビヘイビア呼び出し元モデル * @param array $user ユーザデータ配列 * @return mixed On success Model::$data, false on failure * @throws InternalErrorException */ public function createAvatarAutomatically(Model $model, $user) { //imagickdraw オブジェクトを作成します $draw = new ImagickDraw(); //文字色のセット $draw->setfillcolor('white'); //フォントサイズを 160 に設定します $draw->setFontSize(140); //テキストを追加します $draw->setFont(CakePlugin::path($model->plugin) . 'webroot' . DS . 'fonts' . DS . 'ipaexg.ttf'); $draw->annotation(19, 143, mb_substr(mb_convert_kana($user['User']['handlename'], 'KVA'), 0, 1)); //新しいキャンバスオブジェクトを作成する $canvas = new Imagick(); //ランダムで背景色を指定する $red1 = strtolower(dechex(mt_rand(3, 12))); $red2 = strtolower(dechex(mt_rand(0, 15))); $green1 = strtolower(dechex(mt_rand(3, 12))); $green2 = strtolower(dechex(mt_rand(0, 15))); $blue1 = strtolower(dechex(mt_rand(3, 12))); $blue2 = strtolower(dechex(mt_rand(0, 15))); $canvas->newImage(179, 179, '#' . $red1 . $red2 . $green1 . $green2 . $blue1 . $blue2); //ImagickDraw をキャンバス上に描画します $canvas->drawImage($draw); //フォーマットを PNG に設定します $canvas->setImageFormat('png'); App::uses('TemporaryFolder', 'Files.Utility'); $folder = new TemporaryFolder(); $filePath = $folder->path . DS . Security::hash($user['User']['handlename'], 'md5') . '.png'; $canvas->writeImages($filePath, true); return $filePath; }
public function softThumb($width, $height, $path, $bg = 'transparent') { if ($this->originImage) { echo "\nWrite image to `{$path}`\n"; $resizeParams = $this->getSizes($width, $height); $overlay = clone $this->originImage; $overlay->scaleImage($resizeParams['width'], $resizeParams['height']); $overlayGeo = $overlay->getImageGeometry(); if ($overlayGeo['width'] > $overlayGeo['height']) { $resizeParams['top'] = ($height - $overlayGeo['height']) / 2; $resizeParams['left'] = 0; } else { $resizeParams['top'] = 0; $resizeParams['left'] = ($width - $overlayGeo['width']) / 2; } $thumb = new \Imagick(); $thumb->newImage($width, $height, $bg); $thumb->setImageFormat("png"); $thumb->setCompression(\Imagick::COMPRESSION_ZIP); $thumb->setImageCompressionQuality(0); $thumb->compositeImage($overlay, \Imagick::COMPOSITE_DEFAULT, $resizeParams['left'], $resizeParams['top']); $thumb->writeImageFile(fopen($path, "wb")); $thumb->destroy(); } else { throw new \Exception("As first You must load image", 404); } }
private static function image($frame, $pixelPerPoint = 4, $outerFrame = 4, $format = "png", $quality = 85, $filename = FALSE, $save = TRUE, $print = false) { $imgH = count($frame); $imgW = strlen($frame[0]); $col[0] = new \ImagickPixel("white"); $col[1] = new \ImagickPixel("black"); $image = new \Imagick(); $image->newImage($imgW, $imgH, $col[0]); $image->setCompressionQuality($quality); $image->setImageFormat($format); $draw = new \ImagickDraw(); $draw->setFillColor($col[1]); for ($y = 0; $y < $imgH; $y++) { for ($x = 0; $x < $imgW; $x++) { if ($frame[$y][$x] == '1') { $draw->point($x, $y); } } } $image->drawImage($draw); $image->borderImage($col[0], $outerFrame, $outerFrame); $image->scaleImage(($imgW + 2 * $outerFrame) * $pixelPerPoint, 0); if ($save) { if ($filename === false) { throw new Exception("QR Code filename can't be empty"); } $image->writeImages($filename, true); } if ($print) { Header("Content-type: image/" . $format); echo $image; } }
/** * Outputs the image. * * @see XenForo_Image_Abstract::output() */ public function output($outputType, $outputFile = null, $quality = 85) { $this->_image->stripImage(); // NULL means output directly switch ($outputType) { case IMAGETYPE_GIF: if (is_callable(array($this->_image, 'optimizeimagelayers'))) { $this->_image->optimizeimagelayers(); } $success = $this->_image->setImageFormat('gif'); break; case IMAGETYPE_JPEG: $success = $this->_image->setImageFormat('jpeg') && $this->_image->setImageCompression(Imagick::COMPRESSION_JPEG) && $this->_image->setImageCompressionQuality($quality); break; case IMAGETYPE_PNG: $success = $this->_image->setImageFormat('png'); break; default: throw new XenForo_Exception('Invalid output type given. Expects IMAGETYPE_XXX constant.'); } try { if ($success) { if (!$outputFile) { echo $this->_image->getImagesBlob(); } else { $success = $this->_image->writeImages($outputFile, true); } } } catch (ImagickException $e) { return false; } return $success; }
public function resize($file, $size = array('width' => 100, 'height' => 100), $type = 'png', $fixed = false) { $image = new Imagick($this->file); $image->setBackgroundColor(new ImagickPixel('transparent')); $image->setImageFormat($type); if ($fixed === true) { $newWidth = $size['width']; $newHeight = $size['height']; } else { $imageprops = $image->getImageGeometry(); $width = $imageprops['width']; $height = $imageprops['height']; if ($width > $height) { $newHeight = $size['height']; $newWidth = $size['height'] / $height * $width; } else { $newWidth = $size['width']; $newHeight = $size['width'] / $width * $height; } } $image->resizeImage($newWidth, $newHeight, imagick::FILTER_LANCZOS, 1); $image->writeImage($file . '.' . $type); $image->clear(); $image->destroy(); }
public function getPng($resolutionX = 100, $resolutionY = 100) { $img = new \Imagick(); $img->setResolution($resolutionX, $resolutionY); $img->readImageBlob($this->get()); $img->setImageFormat('png'); return $img->getImageBlob(); }