function wordWrapAnnotation(\Imagick $imagick, $draw, $text, $maxWidth) { $words = explode(" ", $text); $lines = array(); $i = 0; $lineHeight = 0; while ($i < count($words)) { $currentLine = $words[$i]; if ($i + 1 >= count($words)) { $lines[] = $currentLine; break; } //Check to see if we can add another word to this line $metrics = $imagick->queryFontMetrics($draw, $currentLine . ' ' . $words[$i + 1]); while ($metrics['textWidth'] <= $maxWidth) { //If so, do it and keep doing it! $currentLine .= ' ' . $words[++$i]; if ($i + 1 >= count($words)) { break; } $metrics = $imagick->queryFontMetrics($draw, $currentLine . ' ' . $words[$i + 1]); } //We can't add the next word to this line, so loop to the next line $lines[] = $currentLine; $i++; //Finally, update line height if ($metrics['textHeight'] > $lineHeight) { $lineHeight = $metrics['textHeight']; } } return array($lines, $lineHeight); }
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; }
function renderOriginalImage() { $imagick = new \Imagick(realpath("./images/chair.jpeg")); header("Content-Type: image/jpg"); echo $imagick->getImageBlob(); return; }
public function resizeTo($width, $height) { if (osc_use_imagick()) { $bg = new Imagick(); $bg->newImage($width, $height, 'white'); $this->im->thumbnailImage($width, $height, true); $geometry = $this->im->getImageGeometry(); $x = ($width - $geometry['width']) / 2; $y = ($height - $geometry['height']) / 2; $bg->compositeImage($this->im, imagick::COMPOSITE_OVER, $x, $y); $this->im = $bg; } else { $w = imagesx($this->im); $h = imagesy($this->im); if ($w / $h >= $width / $height) { //$newW = $width; $newW = $w > $width ? $width : $w; $newH = $h * ($newW / $w); } else { //$newH = $height; $newH = $h > $height ? $height : $h; $newW = $w * ($newH / $h); } $newIm = imagecreatetruecolor($width, $height); //$newW, $newH); imagealphablending($newIm, false); $colorTransparent = imagecolorallocatealpha($newIm, 255, 255, 255, 127); imagefill($newIm, 0, 0, $colorTransparent); imagesavealpha($newIm, true); imagecopyresampled($newIm, $this->im, ($width - $newW) / 2, ($height - $newH) / 2, 0, 0, $newW, $newH, $w, $h); imagedestroy($this->im); $this->im = $newIm; } return $this; }
function compareFile($injector, $functionFullname, $filename, $fileExtension) { $newFilename = $filename . "new1"; generateCompare($injector, $functionFullname, $newFilename); //echo "Comparing $filename to $newFilename \n"; echo "."; $imagickSrc = new Imagick($filename . $fileExtension); $imagickNew = new Imagick($newFilename . $fileExtension); // const LAYERMETHOD_UNDEFINED = 0; // const LAYERMETHOD_COALESCE = 1; // const LAYERMETHOD_COMPAREANY = 2; // const LAYERMETHOD_COMPARECLEAR = 3; // const LAYERMETHOD_COMPAREOVERLAY = 4; // const LAYERMETHOD_DISPOSE = 5; // const LAYERMETHOD_OPTIMIZE = 6; // const LAYERMETHOD_OPTIMIZEPLUS = 8; // const LAYERMETHOD_OPTIMIZETRANS = 9; // const LAYERMETHOD_COMPOSITE = 12; // const LAYERMETHOD_OPTIMIZEIMAGE = 7; // const LAYERMETHOD_REMOVEDUPS = 10; // const LAYERMETHOD_REMOVEZERO = 11; // const LAYERMETHOD_TRIMBOUNDS = 12; $result = $imagickSrc->compareImages($imagickNew, \Imagick::LAYERMETHOD_COMPAREANY); list($imagickDifference, $distance) = $result; if ($distance > 0.01) { echo "Differrence detected in {$functionFullname} \n"; /** @var $imagickDifference Imagick */ $imagickDifference->writeimage($filename . "diff" . $fileExtension); } }
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); }
protected function save($path) { $pathinfo = pathinfo($path); if (!file_exists($pathinfo['dirname'])) { mkdir($pathinfo['dirname'], 0777, true); } try { $image = new \Imagick($this->source); $image->thumbnailImage($this->width, $this->height, true); if ($this->color) { $thumb = $image; $image = new \Imagick(); $image->newImage($this->width, $this->height, $this->color, $pathinfo['extension']); $size = $thumb->getImageGeometry(); $x = ($this->width - $size['width']) / 2; $y = ($this->height - $size['height']) / 2; $image->compositeImage($thumb, \imagick::COMPOSITE_OVER, $x, $y); $thumb->destroy(); } $image->writeImage($path); $image->destroy(); } catch (\Exception $e) { } return $this; }
/** * {@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; }
/** * Info about driver's version * * @param string $sDriver * * @return bool */ public function GetDriverVersion($sDriver) { $sVersion = false; $sDriver = strtolower($sDriver); if (isset($this->aDrivers[$sDriver])) { if ($this->aDrivers[$sDriver] == 'Imagick') { if (class_exists('Imagick')) { $img = new \Imagick(); $aInfo = $img->getVersion(); $sVersion = $aInfo['versionString']; if (preg_match('/\\w+\\s\\d+\\.[\\d\\.\\-]+/', $sVersion, $aMatches)) { $sVersion = $aMatches[0]; } } } elseif ($this->aDrivers[$sDriver] == 'Gmagick') { if (class_exists('Gmagick')) { $aInfo = Gmagick::getVersion(); $sVersion = $aInfo['versionString']; if (preg_match('/\\w+\\s\\d+\\.[\\d\\.\\-]+/', $sVersion, $aMatches)) { $sVersion = $aMatches[0]; } } } else { if (function_exists('gd_info')) { $aInfo = gd_info(); $sVersion = $aInfo['GD Version']; if (preg_match('/\\d+\\.[\\d\\.]+/', $sVersion, $aMatches)) { $sVersion = $aMatches[0]; } } } } return $sVersion; }
/** * 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 }
/** * * * * Data comes in following format * * array( * <fileId> => <pdfFilePath> * ); * * @param type $data * @return int */ public function createThumbnails($data) { return NULL; if (!extension_loaded('imagick')) { } //die(); $imagick = new \Imagick(); foreach ($data as $fileId => $filePath) { if (is_file($filePath)) { dump($filePath . ' exists'); } } die; if (!file_exists($pdfName)) { return 0; } $pdf = new \Imagick(); $pdf->readImage($pdfName); $pages = count($pdf); $pages = $pages ? $pages + 1 : 0; foreach ($pdf as $index => $image) { $image->setcolorspace(\Imagick::COLORSPACE_RGB); $image->setCompression(\Imagick::COMPRESSION_JPEG); $image->setCompressionQuality(90); $image->setResolution(600, 600); $image->setImageFormat('jpeg'); // $image->resizeImage(405, 574, \Imagick::FILTER_LANCZOS, 1 , TRUE); $image->writeImage($folder . '/' . ($index + 1) . '.jpg'); } $pdf->destroy(); $pages = count(glob($folder . '/*.jpg')); return $pages; }
protected function loadSVG($image) { $this->log('Load SVG image', 2); if (!class_exists('Imagick')) { $this->log('Fail', 2); throw new ImageMagickNotAvailableException(); } $content = @file_get_contents($image); if (!is_string($content)) { $this->log('Fail', 2); throw new InvalidImageException(sprintf('Could not load <info>%s</info>, could not read resource.', $image)); } $image = new \Imagick(); $image->readImageBlob($content); $width = $image->getImageWidth(); $height = $image->getImageHeight(); if (310 > $width || 310 > $height) { $this->log('Fail', 2); throw new InvalidImageException(sprintf('Source image must be at least <info>%s</info>,' . ' actual size is: <info>%s</info>', '310x310', $width . 'x' . $height)); } $image->setImageFormat('png24'); $this->gd = @imagecreatefromstring((string) $image); $image->destroy(); if (!is_resource($this->gd)) { $this->log('Fail', 2); throw new InvalidImageException(sprintf('Could not load <info>%s</info>, ImageMagick could not convert' . ' the resource to a valid GD compatible image.', $image)); } $this->log('Success', 2); return $this; }
/** * アバター自動生成処理 * * @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; }
/** * 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(); }
public function save() { $success = parent::save(); if ($success && isset($this->tempFile)) { $extension = $this->getExtension(); // save original $original = $this->name . "." . $extension; $path = $this->getPath(null, true); $this->logger->log("moving " . $this->tempFile["tmp_name"] . " to " . $path); $success = move_uploaded_file($this->tempFile["tmp_name"], $path); if ($success && $this->isImage()) { $thumbs = array(array('width' => 200, 'suffix' => 'small'), array('width' => 500, 'suffix' => 'med')); foreach ($thumbs as $thumb) { $thumb_path = $this->getPath($thumb['suffix'], true); $this->logger->log("thumbnailing " . $this->tempFile["tmp_name"] . " to " . $thumb_path); $image = new Imagick($path); $image->scaleImage($thumb['width'], 0); $image->writeImage($thumb_path); $image->destroy(); } } else { if (!$success) { $this->errorMessage = "Oops! We had trouble moving the file. Please try again later."; $success = false; } } } else { $this->status = "Sorry, there was an error with the file: " . $this->tempFile["error"]; $success = false; } return $success; }
function __construct($filename) { try { if(extension_loaded('imagick')) { $im = new Imagick(); $im->readImage($filename); $width = $im->getImageWidth(); $height = $im->getImageHeight(); $source = new \Zxing\IMagickLuminanceSource($im, $width, $height); }else { $image = file_get_contents($filename); $sizes = getimagesize($filename); $width = $sizes[0]; $height = $sizes[1]; $im = imagecreatefromstring($image); $source = new \Zxing\GDLuminanceSource($im, $width, $height); } $histo = new Zxing\Common\HybridBinarizer($source); $bitmap = new Zxing\BinaryBitmap($histo); $reader = new Zxing\Qrcode\QRCodeReader(); $this->result = $reader->decode($bitmap); }catch (\Zxing\NotFoundException $er){ $this->result = false; }catch( \Zxing\FormatException $er){ $this->result = false; }catch( \Zxing\ChecksumException $er){ $this->result = false; } }
public function createMissingThumbsAction() { $this->initCommonParams($this->getRequest()); $this->outputMessage('[light_cyan]Creating missing thumbs.'); $dbAdapter = $this->getServiceLocator()->get('dbAdapter'); $apartments = $dbAdapter->createStatement(' SELECT ai.*, a.`name` FROM `ga_apartment_images` ai LEFT JOIN `ga_apartments` a ON ai.`apartment_id` = a.`id` ')->execute(); foreach ($apartments as $apartment) { $this->outputMessage('[cyan]Looking into [light_blue]' . $apartment['name'] . '[cyan] images...'); for ($i = 1; $i <= 32; $i++) { if ($apartment['img' . $i]) { $imgPathComponents = explode('/', $apartment['img' . $i]); $originalFileName = array_pop($imgPathComponents); $originalFilePath = DirectoryStructure::FS_GINOSI_ROOT . DirectoryStructure::FS_IMAGES_ROOT . DirectoryStructure::FS_IMAGES_APARTMENT . $apartment['apartment_id'] . '/' . $originalFileName; $thumbFilePath = str_replace('_orig.', '_555.', $originalFilePath); if (!file_exists($originalFilePath)) { $this->outputMessage('[error] Original file for image ' . $i . ' is missing.'); } else { if (file_exists($thumbFilePath)) { $this->outputMessage('[light_blue] Thumb for image ' . $i . ' exists.'); } else { $thumb = new \Imagick($originalFilePath); $thumb->resizeImage(555, 370, \Imagick::FILTER_LANCZOS, 1); $thumb->writeImage($thumbFilePath); $this->outputMessage('[success] Added thumb for image ' . $i); } } } } } $this->outputMessage('Done!'); }
public function renderOriginalImage() { $imagick = new \Imagick(); header("Content-Type: image/jpg"); echo $imagick->getImageBlob(); return; }
function imagick_thumbnail($image, $timage, $ext, $thumbnail_name, $imginfo) { try { $imagick = new Imagick(); $fullpath = "./" . $this->thumbnail_path . "/" . $timage[0] . "/" . $thumbnail_name; if ($ext == "gif") { $imagick->readImage($image . '[0]'); } else { $imagick->readImage($image); } $info = $imagick->getImageGeometry(); $this->info[0] = $info['width']; $this->info[1] = $info['height']; $imagick->thumbnailImage($this->dimension, $this->dimension, true); if ($ext == "png" || $ext == "gif") { $white = new Imagick(); $white->newImage($this->dimension, $this->dimension, "white"); $white->compositeimage($image, Imagick::COMPOSITE_OVER, 0, 0); $white->writeImage($fullpath); $white->clear(); } else { $imagick->writeImage($fullpath); } $imagick->clear(); } catch (Exception $e) { echo "Unable to load image." . $e->getMessage(); return false; } return true; }
function getPage($page) { $format = $this->parameters['format_image']; switch ($format) { case "imagick": case "png": $extension = "png"; $content_type = "image/x-png"; break; case "jpeg": $extension = "jpg"; $content_type = "image/jpeg"; break; } $len = strlen($this->getPageCount()); if (!file_exists($this->doc->driver->get_cached_filename($this->doc->id) . "-" . str_pad($page, $len, "0", STR_PAD_LEFT) . "." . $extension)) { $resolution = $this->parameters['resolution_image']; if ($format == "imagick") { exec("pdftoppm -f {$page} -l {$page} -r " . $resolution . " " . $this->doc->driver->get_cached_filename($this->doc->id) . " " . $this->doc->driver->get_cached_filename("page_" . $this->doc->id)); $imagick = new Imagick(); $imagick->setResolution($resolution, $resolution); $imagick->readImage($this->doc->driver->get_cached_filename("page_" . $this->doc->id) . "-" . str_pad($page, $len, "0", STR_PAD_LEFT) . ".ppm"); $imagick->writeImage($this->doc->driver->get_cached_filename("page_" . $this->doc->id) . "-" . str_pad($page, $len, "0", STR_PAD_LEFT) . ".png"); unlink($this->doc->driver->get_cached_filename("page_" . $this->doc->id) . "-" . str_pad($page, $len, "0", STR_PAD_LEFT) . ".ppm"); } else { exec("pdftoppm -f {$page} -l {$page} -r " . $resolution . " -" . $format . " " . $this->doc->driver->get_cached_filename($this->doc->id) . " " . $this->doc->driver->get_cached_filename("page_" . $this->doc->id)); } } if (file_exists($this->doc->driver->get_cached_filename("page_" . $this->doc->id) . "-" . str_pad($page, $len, "0", STR_PAD_LEFT) . "." . $extension)) { header("Content-Type: " . $content_type); print file_get_contents($this->doc->driver->get_cached_filename("page_" . $this->doc->id) . "-" . str_pad($page, $len, "0", STR_PAD_LEFT) . "." . $extension); } }
/** * Reduces colors of a given image * * @param Intervention\Image\Image $image * @return boolean */ public function execute($image) { $count = $this->argument(0)->value(); $matte = $this->argument(1)->value(); // get current image size $size = $image->getSize(); // build 2 color alpha mask from original alpha $alpha = clone $image->getCore(); $alpha->separateImageChannel(\Imagick::CHANNEL_ALPHA); $alpha->transparentPaintImage('#ffffff', 0, 0, false); $alpha->separateImageChannel(\Imagick::CHANNEL_ALPHA); $alpha->negateImage(false); if ($matte) { // get matte color $mattecolor = $image->getDriver()->parseColor($matte)->getPixel(); // create matte image $canvas = new \Imagick(); $canvas->newImage($size->width, $size->height, $mattecolor, 'png'); // lower colors of original and copy to matte $image->getCore()->quantizeImage($count, \Imagick::COLORSPACE_RGB, 0, false, false); $canvas->compositeImage($image->getCore(), \Imagick::COMPOSITE_DEFAULT, 0, 0); // copy new alpha to canvas $canvas->compositeImage($alpha, \Imagick::COMPOSITE_COPYOPACITY, 0, 0); // replace core $image->setCore($canvas); } else { $image->getCore()->quantizeImage($count, \Imagick::COLORSPACE_RGB, 0, false, false); $image->getCore()->compositeImage($alpha, \Imagick::COMPOSITE_COPYOPACITY, 0, 0); } return true; }
/** * 生成验证码 * @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); } } }
public function __construct(EntityManager $entityManager) { // Tag $this->add(array('name' => 'tag', 'required' => true, 'filters' => array(), 'validators' => array(array('name' => 'NotEmpty', 'break_chain_on_failure' => true, 'options' => array('messages' => array(\Zend\Validator\NotEmpty::IS_EMPTY => 'Please enter a Squad Tag')))))); // Name $this->add(array('name' => 'name', 'required' => true, 'filters' => array(), 'validators' => array(array('name' => 'NotEmpty', 'break_chain_on_failure' => true, 'options' => array('messages' => array(\Zend\Validator\NotEmpty::IS_EMPTY => 'Please enter a Squad Name')))))); // Homepage $this->add(array('name' => 'homepage', 'required' => false, 'filters' => array(), 'validators' => array(array('name' => 'Zend\\Validator\\Uri', 'break_chain_on_failure' => true, 'options' => array('allowRelative' => false, 'messages' => array(\Zend\Validator\Uri::INVALID => 'FRONTEND_SQUAD_URL_INVALID_FORMAT', \Zend\Validator\Uri::NOT_URI => 'FRONTEND_SQUAD_URL_INVALID_FORMAT')))))); // Title $this->add(array('name' => 'title', 'required' => false, 'filters' => array(), 'validators' => array())); // Email $this->add(array('name' => 'email', 'required' => false, 'filters' => array(), 'validators' => array(array('name' => 'Zend\\Validator\\EmailAddress', 'break_chain_on_failure' => true, 'options' => array('messages' => array(\Zend\Validator\EmailAddress::INVALID => 'FRONTEND_SQUAD_EMAIL_INVALID_FORMAT')))))); // DeleteLogo $this->add(array('name' => 'deleteLogo', 'required' => false, 'filters' => array(), 'validators' => array())); // Upload $this->add(array('name' => 'logo', 'required' => false, 'filters' => array(), 'validators' => array(array('name' => 'Zend\\Validator\\File\\Extension', 'break_chain_on_failure' => true, 'options' => array('extension' => array('jpg', 'jpeg', 'gif', 'png'), 'messages' => array(\Zend\Validator\File\Extension::FALSE_EXTENSION => 'Es werden folgende Logos unterstützt: png,jpg,jpeg,gif'))), array('name' => 'Callback', 'options' => array('message' => array(\Zend\Validator\Callback::INVALID_VALUE => 'FRONTEND_SQUAD_LOGO_INVALID_FORMAT'), 'callback' => function ($value) { if ($value['error'] != 0) { return false; } try { $image = new \Imagick($value['tmp_name']); if ($image->getimageheight() == $image->getimagewidth() && in_array($image->getimageheight(), array(16, 32, 64, 128, 256))) { return true; } else { return false; } } catch (\Exception $e) { return false; } return false; }))))); }
/** * Get the average pixel colour from the given file using Image Magick * * @param string $filename * @param bool $as_hex Set to true, the function will return the 6 character HEX value of the colour. * If false, an array will be returned with r, g, b components. */ function get_average_colour($filename, $as_hex_string = true) { try { // Read image file with Image Magick $image = new Imagick($filename); // Scale down to 1x1 pixel to make Imagick do the average $image->scaleimage(1, 1); /** @var ImagickPixel $pixel */ if (!($pixels = $image->getimagehistogram())) { return null; } } catch (ImagickException $e) { // Image Magick Error! return null; } catch (Exception $e) { // Unknown Error! return null; } $pixel = reset($pixels); $rgb = $pixel->getcolor(); if ($as_hex_string) { return sprintf('%02X%02X%02X', $rgb['r'], $rgb['g'], $rgb['b']); } return $rgb; }
/** * Returns whether image manipulations will be performed using GD or not. * * @return bool|null */ public function isGd() { if ($this->_isGd === null) { if (craft()->config->get('imageDriver') == 'gd') { $this->_isGd = true; } else if (extension_loaded('imagick')) { // Taken from Imagick\Imagine() constructor. $imagick = new \Imagick(); $v = $imagick->getVersion(); list($version, $year, $month, $day, $q, $website) = sscanf($v['versionString'], 'ImageMagick %s %04d-%02d-%02d %s %s'); // Update this if Imagine updates theirs. if (version_compare('6.2.9', $version) <= 0) { $this->_isGd = false; } else { $this->_isGd = true; } } else { $this->_isGd = true; } } return $this->_isGd; }
protected function invokeHandler() { $specific = array(); $size = getimagesize($this->file->getAbsPath()); if ($size !== false) { $specific['imagesize'] = $size[0] . ' x ' . $size[1] . ' px'; } else { $specific['imagesize'] = System::getLanguage()->_('Unknown'); } if (extension_loaded('imagick') && class_exists('Imagick')) { try { $i = new Imagick($this->file->getAbsPath()); $specific['format'] = $i->getimageformat(); } catch (Exception $e) { Log::handleException($e, false); if ($this->file->ext == "svg") { Log::sysLog('ImageHandler', '"librsvg" is not installed. Without it Imagick could not handle .svg files!'); } } } else { $specific['format'] = System::getLanguage()->_('Unknown'); } $this->smarty->assign('specific', $specific); $this->smarty->display('handler/image.tpl'); }
/** * 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); }
function compareImage(URLToCheck $urlToCheck, $resposeBody, $contentType) { $imageType = substr($contentType, strlen('image/')); $blahblah = str_replace(['?', '&', '/', '='], '_', $urlToCheck->getUrl()); if (strlen($blahblah) >= 100) { $md5 = md5($blahblah); $blahblah = substr($blahblah, 0, 100) . $md5; } $oututFilename = 'compare/' . $blahblah . '.' . $imageType; if (file_exists($oututFilename) == false) { echo "First compare, creating file of {$blahblah}\n"; file_put_contents($oututFilename, $resposeBody); return; } $imagickNew = new Imagick(); $imagickNew->readimageblob($resposeBody); $imagickCompare = new Imagick($oututFilename); $result = $imagickCompare->compareImages($imagickNew, \Imagick::LAYERMETHOD_COMPAREANY); list($imagickDifference, $distance) = $result; if ($distance > 0.01) { echo "Differrence detected in {$blahblah} \n"; /** @var $imagickDifference Imagick */ $imagickDifference->writeimage($blahblah . "diff" . time() . '.' . $imageType); } }
/** * @param $file * @return string */ public function thumbnail($file) { $format = ''; $name = md5((new \DateTime())->format('c')); foreach ($this->sizes as $size) { $image = new \Imagick($file); $imageRatio = $image->getImageWidth() / $image->getImageHeight(); $width = $size['width']; $height = $size['height']; $customRation = $width / $height; if ($customRation < $imageRatio) { $widthThumb = 0; $heightThumb = $height; } else { $widthThumb = $width; $heightThumb = 0; } $image->thumbnailImage($widthThumb, $heightThumb); $image->cropImage($width, $height, ($image->getImageWidth() - $width) / 2, ($image->getImageHeight() - $height) / 2); $image->setCompressionQuality(100); $format = strtolower($image->getImageFormat()); $pp = $this->cachePath . '/' . $size['name'] . "_{$name}." . $format; $image->writeImage($pp); } return "_{$name}." . $format; }