/** * {@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; }
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'); } }
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; }
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 convert(string $file, Conversion $conversion = null) : string { $imageFile = pathinfo($file, PATHINFO_DIRNAME) . '/' . pathinfo($file, PATHINFO_FILENAME) . '.jpg'; $image = new \Imagick(); $image->readImage($file); $image->setBackgroundColor(new ImagickPixel('none')); $image->setImageFormat('jpg'); file_put_contents($imageFile, $image); return $imageFile; }
function upload() { // Default settings/restrictions $config['upload_path'] = $this->directory; $config['allowed_types'] = 'gif|jpg|png|jpeg'; $config['max_size'] = min(maxUploadSizeBytes() / 1024, self::MAX_FILE_SIZE_KB); $config['max_width'] = '0'; // no restriction (image will be resized anyway!) $config['max_height'] = '0'; $config['max_filename'] = self::MAX_FILE_NAME_LEN; $this->load->library('upload', $config); // Try and upload the file using the settings from __construct() if (!$this->upload->do_upload('new_file')) { // Abort upload and display errors, if any $data['error_message'] = $this->upload->display_errors(); $data['recent_uploads'] = $this->getRecentUploads(); $data['title'] = "Image Uploader"; $data['js_lib'] = array('core'); $this->load->view('uploader', $data); } else { // Create the compressed copy of the image based on a hash of the uploaded filename $upload_result = $this->upload->data(); $image = new Imagick($this->directory . $upload_result['file_name']); $image->setBackgroundColor(new ImagickPixel('white')); // Create the optimised image // "bestfit" param will ensure that the image is downscaled proportionally if needed // if ($image->getImageWidth() >= $image->getImageHeight() // && $image->getImageWidth() > self::IMAGE_LANDSCAPE_WIDTH || $image->getImageHeight() > self::IMAGE_LANDSCAPE_HEIGHT) // { // $image->resizeImage(self::IMAGE_LANDSCAPE_WIDTH,self::IMAGE_LANDSCAPE_HEIGHT, Imagick::FILTER_LANCZOS, 1, true); // } // else if ($image->getImageWidth() > self::IMAGE_PORTRAIT_WIDTH || $image->getImageHeight() > self::IMAGE_PORTRAIT_HEIGHT) // { // $image->resizeImage(self::IMAGE_PORTRAIT_WIDTH,self::IMAGE_PORTRAIT_HEIGHT, Imagick::FILTER_LANCZOS, 1, true); // } $flattened = new IMagick(); $flattened->newImage($image->getImageWidth(), $image->getImageHeight(), new ImagickPixel("white")); $flattened->compositeImage($image, imagick::COMPOSITE_OVER, 0, 0); $flattened->setImageFormat("jpg"); $flattened->setImageCompression(Imagick::COMPRESSION_JPEG); // $flattened->setCompression(Imagick::COMPRESSION_JPEG); // $flattened->setCompressionQuality(self::COMPRESSION_PERCENTAGE); $flattened->writeImage($this->directory . 'img_' . md5($upload_result['file_name']) . ".jpg"); $flattened->clear(); $flattened->destroy(); $image->clear(); $image->destroy(); $data['success_message'] = "File successfully uploaded!"; $data['recent_uploads'] = $this->getRecentUploads(); $data['title'] = "Image Uploader"; $data['js_lib'] = array('core'); $data['max_filesize'] = $config['max_size']; $this->load->view('uploader', $data); } }
/** * @param null|string $backgroundColor * * @throws ProcessorException * * @returns $this */ public function removeAlpha($backgroundColor = null) { $backgroundColor = $backgroundColor === null ? 'white' : $backgroundColor; try { $this->im->setBackgroundColor($backgroundColor); $this->im->setImageAlphaChannel($this->getLibraryConstant('ALPHACHANNEL_REMOVE', null, 11)); } catch (\Exception $e) { throw new ProcessorException('Could not remove alpha channel: %s', null, $e, (string) $e->getMessage()); } return $this; }
protected function _imageResizeAndSave($object) { $path = APPLICATION_ROOT . '/public_html/images/eyecatchers/'; $system->lng = $this->_getParam('lng'); $adapter = new Zend_File_Transfer_Adapter_Http(); $adapter->setDestination($path); $adapter->setOptions(array('ignoreNoFile' => true)); if (!$adapter->receive()) { $msgr = Sanmax_MessageStack::getInstance('SxModule_Eyecatchers_Validator'); $msgr->addMessage('file', $adapter->getMessages(), 'title'); } if ($object->getPicture() == null) { $object->setPicture(''); } $files = $adapter->getFileInfo(); foreach ($files as $file) { if (!$file['tmp_name']) { continue; } $path0 = $path . "253x115/"; $path1 = $path . "980x450/"; if (!is_dir($path0)) { mkdir($path0, 0777, true); } if (!is_dir($path1)) { mkdir($path1, 0777, true); } $filename = $object->createThumbName($file['name']) . '_' . time() . '.png'; $image = new Imagick($file['tmp_name']); $image->cropThumbnailImage(253, 115); $image->setCompression(Imagick::COMPRESSION_JPEG); $image->setImageCompressionQuality(100); $image->setBackgroundColor(new ImagickPixel('transparent')); $image->setImageFormat('png32'); $image->writeImage($path0 . $filename); $image->clear(); $image->destroy(); $image = new Imagick($file['tmp_name']); $image->cropThumbnailImage(980, 450); $image->setCompression(Imagick::COMPRESSION_JPEG); $image->setImageCompressionQuality(75); $image->setBackgroundColor(new ImagickPixel('transparent')); $image->setImageFormat('png32'); $image->writeImage($path1 . $filename); $image->clear(); $image->destroy(); unlink($file['tmp_name']); $object->setPicture($filename); } }
/** * Initiates new image from path in filesystem * * @param string $path * @return \Intervention\Image\Image */ public function initFromPath($path) { $core = new \Imagick(); try { $core->setBackgroundColor(new \ImagickPixel('transparent')); $core->readImage($path); $core->setImageType(\Imagick::IMGTYPE_TRUECOLORMATTE); } catch (\ImagickException $e) { throw new \Intervention\Image\Exception\NotReadableException("Unable to read image from path ({$path}).", 0, $e); } // build image $image = $this->initFromImagick($core); $image->setFileInfoFromPath($path); return $image; }
function __construct($src, $dst, $flatten) { parent::__construct($dst); if ($src instanceof Strass_Vignette_Imagick) { $image = $src->image; } else { $image = new Imagick(); $image->setBackgroundColor(new ImagickPixel('transparent')); $image->readImage($src); if ($flatten) { $photo = $image; $image = new Imagick(); $image->newImage($photo->getImageWidth(), $photo->getImageHeight(), "white"); $image->compositeImage($photo, Imagick::COMPOSITE_OVER, 0, 0); } } $this->image = $image; }
private function setThumbnails() { $thumbnailsToCreate = ['small', 'large']; foreach ($thumbnailsToCreate as $size) { $lengthDimension = $size == 'small' ? $this->smallThumbnailSize : $this->largeThumbnailSize; // PDFs, One day learn to extract thumbnails for all the other media types too if ($this->fileinfo['filetype'] == 'pdf' && $this->fileinfo['mime'] == 'application/pdf') { $image = new \Imagick(public_path() . '/' . $this->directory['full'] . $this->fileinfo['filename'] . '[0]'); // Use PNG because: http://stackoverflow.com/questions/10934456/imagemagick-pdf-to-jpgs-sometimes-results-in-black-background $image->setImageFormat('png'); $image->setBackgroundColor(new \ImagickPixel('white')); $image->thumbnailImage($lengthDimension, $lengthDimension, true); // http://php.net/manual/en/imagick.flattenimages.php#101164 $image = $image->flattenImages(); $image->setImageFormat('jpg'); $image->writeImage(public_path() . '/' . $this->directory[$size] . $this->fileinfo['filename_without_extension'] . '.jpg'); } } }
/** * Get the svg as an image * * @return \Imagecow\Image */ public function get($width = 0, $height = 0) { $imageWidth = $this->image->getImageWidth(); $imageHeight = $this->image->getImageHeight(); if ($width !== 0 && ($height === 0 || $imageWidth / $width > $imageHeight / $height)) { $height = ceil($width / $imageWidth * $imageHeight); } elseif ($height !== 0) { $width = ceil($height / $imageHeight * $imageWidth); } else { $width = $imageWidth; $height = $imageHeight; } $image = new \Imagick(); $image->setBackgroundColor(new \ImagickPixel('transparent')); $image->setResolution($width, $height); $blob = $this->image->getImageBlob(); $blob = preg_replace('/<svg([^>]*) width="([^"]*)"/si', '<svg$1 width="' . $width . 'px"', $blob); $blob = preg_replace('/<svg([^>]*) height="([^"]*)"/si', '<svg$1 height="' . $height . 'px"', $blob); $image->readImageBlob($blob); $image->setImageFormat("png"); return new \Imagecow\Image(new \Imagecow\Libs\Imagick($image)); }
/** * Generate a derivative image with Imagick. */ public function createImage($sourcePath, $destPath, $type, $sizeConstraint, $mimeType) { $page = (int) $this->getOption('page', 0); try { $imagick = new Imagick($sourcePath . '[' . $page . ']'); } catch (ImagickException $e) { _log("Imagick failed to open the file. Details:\n{$e}", Zend_Log::ERR); return false; } $origX = $imagick->getImageWidth(); $origY = $imagick->getImageHeight(); $imagick->setImagePage($origX, $origY, 0, 0); $imagick->setBackgroundColor('white'); $imagick->setImageBackgroundColor('white'); $imagick = $imagick->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN); if ($type != 'square_thumbnail') { $imagick->thumbnailImage($sizeConstraint, $sizeConstraint, true); } else { // We could use cropThumbnailImage here but it lacks support for // the gravity setting if ($origX < $origY) { $newX = $sizeConstraint; $newY = $origY * ($sizeConstraint / $origX); $offsetX = 0; $offsetY = $this->_getCropOffsetY($newY, $sizeConstraint); } else { $newY = $sizeConstraint; $newX = $origX * ($sizeConstraint / $origY); $offsetY = 0; $offsetX = $this->_getCropOffsetX($newX, $sizeConstraint); } $imagick->thumbnailImage($newX, $newY); $imagick->cropImage($sizeConstraint, $sizeConstraint, $offsetX, $offsetY); $imagick->setImagePage($sizeConstraint, $sizeConstraint, 0, 0); } $imagick->writeImage($destPath); $imagick->clear(); return true; }
public function resizeAndSave() { $path = APPLICATION_ROOT . '/public_html/images/doctors/'; if (!is_dir($path)) { mkdir($path, 0777, true); } $adapter = new Zend_File_Transfer_Adapter_Http(); $adapter->setDestination($path); $adapter->setOptions(array('ignoreNoFile' => true)); if (!$adapter->receive()) { $msgr = Sanmax_MessageStack::getInstance('SxModule_Doctor'); $msgr->addMessage('file', $adapter->getMessages(), 'file'); } $files = $adapter->getFileInfo(); foreach ($files as $file) { if ($file['tmp_name'] == '') { continue; } $filename = $this->_doc->createThumbName($file['name']) . '_' . time() . '.png'; $path0 = $path . "100x100/"; $path1 = $path . "230x230/color/"; $path2 = $path . "230x230/fade/"; $path3 = $path . "110x110/color/"; $path4 = $path . "110x110/fade/"; if (!is_dir($path0)) { mkdir($path0, 0777, true); } if (!is_dir($path1)) { mkdir($path1, 0777, true); } if (!is_dir($path2)) { mkdir($path2, 0777, true); } if (!is_dir($path3)) { mkdir($path3, 0777, true); } if (!is_dir($path4)) { mkdir($path4, 0777, true); } $image = new Imagick($file['tmp_name']); $image->cropThumbnailImage(100, 100); $image->setCompression(Imagick::COMPRESSION_JPEG); $image->setImageCompressionQuality(100); $image->setBackgroundColor(new ImagickPixel('transparent')); $image->setImageFormat('png32'); $image->writeImage($path0 . $filename); $image->clear(); $image->destroy(); $image1 = new Imagick($file['tmp_name']); $image1->cropThumbnailImage(230, 230); $image1->setCompression(Imagick::COMPRESSION_JPEG); $image1->setImageCompressionQuality(100); $image1->setBackgroundColor(new ImagickPixel('transparent')); $image1->setImageFormat('png32'); $image1->writeImage($path1 . $filename); $image1->setimagetype(Imagick::IMGTYPE_GRAYSCALE); $image1->writeImage($path2 . $filename); $image1->clear(); $image1->destroy(); $image1 = new Imagick($file['tmp_name']); $image1->cropThumbnailImage(110, 110); $image1->setCompression(Imagick::COMPRESSION_JPEG); $image1->setImageCompressionQuality(100); $image1->setBackgroundColor(new ImagickPixel('transparent')); $image1->setImageFormat('png32'); $image1->writeImage($path3 . $filename); $image1->setimagetype(Imagick::IMGTYPE_GRAYSCALE); $image1->writeImage($path4 . $filename); $image1->clear(); $image1->destroy(); unlink($file['tmp_name']); $this->_doc->setPhoto($filename); } }
public function diyAction() { Yaf_Dispatcher::getInstance()->autoRender(FALSE); $id = $this->_req->getQuery('id', 1); if ($this->_req->isPost()) { $this->diy = new DiyModel(); $pre_svg = '<?xml version="1.0" standalone="no" ?>' . trim($_POST['svg_val']); $rdate = APPLICATION_PATH . '/public/Uploads/' . date("Ymd", time()); //文件名 if (!file_exists($rdate)) { chmod(APPLICATION_PATH . '/public/Uploads/', 0777); mkdir($rdate); //创建目录 } $savename = $this->create_unique(); $path = $rdate . '/' . $savename; if (!($file_svg = fopen($path . '.svg', 'w+'))) { echo "不能打开文件 {$path}.'.svg'"; exit; } if (fwrite($file_svg, $pre_svg) === FALSE) { echo "不能写入到文件 {$path}.'.svg'"; exit; } echo "已成功写入"; fclose($file_svg); //$path= APPLICATION_PATH . '/public/Uploads/' . date("Ymd", time()) .'/m-1'; //添加图片转化 $im = new Imagick(); $im->setBackgroundColor(new ImagickPixel('transparent')); $svg = file_get_contents($path . '.svg'); $im->readImageBlob($svg); $im->setImageFormat("png"); $am = $im->writeImage($path . '.png'); $im->thumbnailImage(579, 660, true); /* 改变大小 */ $ams = $im->writeImage($path . '-t.png'); $im->clear(); $im->destroy(); //图片加水印 $waterpath = APPLICATION_PATH . '/public/source/source.png'; $im1 = new Imagick($waterpath); $im2 = new Imagick($path . '.png'); $im2->thumbnailImage(600, 600, true); $dw = new ImagickDraw(); $dw->setGravity(5); $dw->setFillOpacity(0.1); $dw->composite($im2->getImageCompose(), 0, 0, 50, 0, $im2); $im1->drawImage($dw); if (!$im1->writeImage($path . '-s.png')) { echo '加水印失败'; exit; } $im1->clear(); $im2->clear(); $im1->destroy(); $im2->destroy(); //exit; //删除相应的文件 //unlink($path.'.svg'); //unlink($path.'.png'); $filepath = '/Uploads/' . date("Ymd", time()) . '/' . $savename . '.png'; $data['origin_img'] = $filepath; $data['diy_synthetic_img'] = '/Uploads/' . date("Ymd", time()) . '/' . $savename . '-s.png'; $data['diy_preview_img'] = '/Uploads/' . date("Ymd", time()) . '/' . $savename . '-s.png'; $data['user_id'] = 0; $data['source'] = 3; $data['created'] = date("Y-m-d H:i:s", time()); $datas['image'] = $data['diy_synthetic_img']; $datas['user_id'] = 0; $datas['source'] = 2; $datas['state'] = 1; $datas['createtime'] = date("Y-m-d H:i:s", time()); $datas['updatetime'] = date("Y-m-d H:i:s", time()); $diy_picture_id = $this->diy->adddiy($data); //$datas['use'] = $tool; //$datas['author'] = $userinfo['mobile']; $this->userpicture = new UserpictureModel(); $datas['diy_picture_id'] = $diy_picture_id; $this->userpicture->adduserpicture($datas); $response_data['origin_img'] = '/Uploads/' . date("Ymd", time()) . '/' . $savename . '.png'; $response_data['diy_preview_img'] = '/Uploads/' . date("Ymd", time()) . '/' . $savename . '-s.png'; $response_data['diy_thumb_img'] = '/Uploads/' . date("Ymd", time()) . '/' . $savename . '-t.png'; $response_data['diy_picture_id'] = $diy_picture_id; //$this->getView()->display("/index/buy.html",$response_data); $this->_session->set('diypicture', $response_data); $this->_redis = new phpredis(); $this->_redis->set($diy_picture_id, json_encode($response_data)); header("Location:/index/share?diy=" . $diy_picture_id); } else { switch ($id) { case 1: $this->getView()->display("index/diy_1.html"); break; case 2: $this->getView()->display("index/diy_2.html"); break; case 3: $this->getView()->display("index/diy_3.html"); break; case 4: $this->getView()->display("index/diy_4.html"); break; case 5: $this->getView()->display("index/diy_5.html"); break; case 6: $this->getView()->display("index/diy_6.html"); break; case 7: $this->getView()->display("index/diy_7.html"); break; } } }
private function convert($srcimage, $force) { $response = array("image" => $srcimage, "error" => false, "msg" => "Image converted succesfully"); // Check if image is datauri or url if (preg_match("/^data:image\\/svg\\+xml/", $srcimage) == 1) { $response["type"] = "datauri"; $filename = md5($srcimage); $response["filename"] = $filename; // Prepare the new $srcimage and secode $srcimage = str_replace("data:image/svg+xml;base64,", "", $srcimage); $srcimage = base64_decode($srcimage); } else { $response["type"] = "url"; // Get the filename from the url $filename = explode('/', $srcimage); $filename = array_pop($filename); $filename = str_replace('.svg', '', $filename); $response["filename"] = $filename; } // Check if file already exists if (file_exists($this->sitedirectory . '/' . $filename . '.png') && $force != "true") { $lastmodified = filemtime($this->sitedirectory . '/' . $filename . '.png'); $response["image"] = $this->publicurl . "/" . $filename . ".png"; $response["msg"] = "Image retrieved from cache. Saved at: " . date("Y-m-d H:i:s", $lastmodified); return $response; // Kill and return response } // Check if we can reach the provided URL // return the response when the image can't be reached if ($response["type"] == "url") { $check = $this->checksrcurl($srcimage); if ($check > 300 || $check == false) { $response["error"] = true; $response["msg"] = "Couldn't download image from provided URL"; return $response; // Kill and return response } } // download the image if given srcimage is an url if ($response["type"] == "url") { $srcimage = file_get_contents($srcimage); } // Convert $srcimage to PNG try { $desimage = new Imagick(); $desimage->setBackgroundColor(new ImagickPixel('transparent')); $desimage->readImageBlob($srcimage); $desimage->setImageFormat("png32"); $desimage->setImageCompressionQuality(100); // Remove if dumpcache is enabled if ($force && file_exists($this->sitedirectory . '/' . $filename . '.png')) { unlink($this->sitedirectory . '/' . $filename . '.png'); } // Save the file file_put_contents($this->sitedirectory . '/' . $filename . '.png', $desimage); // Set the URL where the PNG can be viewed from $response["image"] = $this->publicurl . "/" . $filename . ".png"; } catch (ImagickException $e) { $response["error"] = true; $response["msg"] = $e->getMessage(); } // Return response return $response; }
/** * @param string $imageBlob * @param float $resolutionX * @param float $resolutionY * @param string|null $backgroundColor * @return CM_Image_Image * @throws CM_Exception_Invalid */ public static function createFromSVG($imageBlob, $resolutionX, $resolutionY, $backgroundColor = null) { $imageBlob = (string) $imageBlob; if ('<?xml' !== substr($imageBlob, 0, 5)) { $imageBlob = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>' . $imageBlob; } $imagick = new Imagick(); $imagick->setResolution((double) $resolutionX, (double) $resolutionY); if (null !== $backgroundColor) { $backgroundColor = (string) $backgroundColor; } else { $backgroundColor = new ImagickPixel('transparent'); } $imagick->setBackgroundColor($backgroundColor); try { $imagick->readImageBlob($imageBlob); } catch (ImagickException $e) { throw new CM_Exception_Invalid('Cannot load Imagick instance', null, ['originalExceptionMessage' => $e->getMessage()]); } return new self($imagick); }
public function makeGradientImage($throw = false) { $this->_initData(); $svg = $this->getSvg(); $im = new Imagick(); $im->setBackgroundColor(new ImagickPixel('transparent')); if (count($this->_stoppoints) < 2) { if ($throw) { throw new Exception("Invalid gradient, not enough stop points"); } else { return "//cdn.virtuosoft.eu/virtuosoft.eu/resources/css3-gradient-generator.png"; } } $im->setBackgroundColor(new ImagickPixel('transparent')); $im->readImageBlob('<?xml version="1.0" encoding="UTF-8" standalone="no"?>' . $svg); $im->setImageFormat("png32"); $this->_image = $im->getImageBlob(); $im->clear(); $im->destroy(); }
private function _isLightImage($imageData) { $image = new Imagick(); $image->readImageBlob($imageData['contents']); $max = $image->getQuantumRange(); $max = $max["quantumRangeLong"]; $image->setImageType(Imagick::IMGTYPE_GRAYSCALEMATTE); $float = 0.5; $image->thresholdImage($float * $max, 255); $image->setBackgroundColor('white'); $black = 0; $white = 0; for ($x = 0; $x < $image->getImageWidth(); $x++) { for ($y = 0; $y < $image->getImageHeight(); $y++) { $pixel = $image->getImagePixelColor($x, $y); $value = $pixel->getColor(); if ($value['r'] == 0 && $value['g'] == 0 && $value['b'] == 0) { $black++; } else { $white++; } } } return $white > $black; }
public function addTextBox($text, $x1, $y1, $x2, $y2) { $textbox = new \Imagick(); $textbox->setFont(self::$config['font']); $textbox->setBackgroundColor('transparent'); $textbox->setGravity(imagick::GRAVITY_CENTER); // 'label' sticks the string on one line, whereas 'caption' will make a paragraph. // Unfortunately, will happily split two words onto two lines which looks a bit silly // if ($text has two words) then... if (count(explode(" ", trim($text))) == 2) { $method = 'label'; } else { $method = 'caption'; } $textbox->newPseudoImage($x2 - $x1, $y2 - $y1, $method . ":" . $text); $this->image->compositeImage($textbox, imagick::COMPOSITE_OVER, $x1, $y1); return $this; }
public static function thumbnail($item, $width = 0, $height = 0, $border = true, $ftname = '', $quality = 95, $scale_up_force = false) { if (is_numeric($item)) { $f = new file(); $f->load($item); $item = $f; } if (!get_class($item) == 'file') { return; } // precondition, the original image file must exist if (!file_exists($item->absolute_path()) || filesize($item->absolute_path()) < 1) { return; } $original = $item->absolute_path(); $thumbnail = ''; $item_id = $item->id; if (!empty($ftname)) { $item_id = $ftname; } else { if (!is_numeric($item_id)) { $item_id = md5($item->id); } } if ($border === true || $border === 'true' || $border === 1) { $border = 1; } else { $border = 0; } // do we have the thumbnail already created for this image? // option A) opaque JPEG FILE $thumbnail_path_jpg = NAVIGATE_PRIVATE . '/' . $item->website . '/thumbnails/' . $width . 'x' . $height . '-' . $border . '-' . $quality . '-' . $item_id . '.jpg'; if (file_exists($thumbnail_path_jpg)) { // ok, a file exists, but it's older than the image file? (original image file has changed) if (filemtime($thumbnail_path_jpg) > filemtime($original)) { // the thumbnail already exists and is up to date $thumbnail = $thumbnail_path_jpg; } } // option B) transparent PNG FILE $thumbnail_path_png = NAVIGATE_PRIVATE . '/' . $item->website . '/thumbnails/' . $width . 'x' . $height . '-' . $border . '-' . $item_id; if (file_exists($thumbnail_path_png)) { // ok, a file exists, but it's older than the image file? (original image file has changed) if (filemtime($thumbnail_path_png) > filemtime($original)) { // the thumbnail already exists and is up to date $thumbnail = $thumbnail_path_png; } } // do we have to create a new thumbnail if (empty($thumbnail) || isset($_GET['force']) || !(file_exists($thumbnail) && filesize($thumbnail) > 0)) { $thumbnail = $thumbnail_path_png; $handle = new upload($original); $size = array('width' => $handle->image_src_x, 'height' => $handle->image_src_y); $handle->image_convert = 'png'; $handle->file_max_size = '512M'; // maximum image size: 512M (it really depends on available memory) // if needed, calculate width or height with aspect ratio if (empty($width)) { if (!empty($size['height'])) { $width = round($height / $size['height'] * $size['width']); } else { $width = NULL; } return file::thumbnail($item, $width, $height, $border, $ftname); } else { if (empty($height)) { if (!empty($size['width'])) { $height = round($width / $size['width'] * $size['height']); } else { $height = NULL; } return file::thumbnail($item, $width, $height, $border, $ftname); } } $handle->image_x = $width; $handle->image_y = $height; if ($size['width'] < $width && $size['height'] < $height) { // the image size is under the requested width / height? => fill around with transparent color $handle->image_default_color = '#FFFFFF'; $handle->image_resize = true; $handle->image_ratio_no_zoom_in = true; $borderP = array(floor(($height - $size['height']) / 2), ceil(($width - $size['width']) / 2), ceil(($height - $size['height']) / 2), floor(($width - $size['width']) / 2)); $handle->image_border = $borderP; if ($scale_up_force) { $handle->image_border = array(); if ($height > width) { $handle->image_ratio_y = true; } else { $handle->image_ratio_x = true; } } $handle->image_border_color = '#FFFFFF'; $handle->image_border_opacity = 0; } else { // the image size is bigger than the requested width / height, we must resize it $handle->image_default_color = '#FFFFFF'; $handle->image_resize = true; $handle->image_ratio_fill = true; } if ($border == 0) { $handle->image_border = false; $handle->image_ratio_no_zoom_in = false; if (!empty($item->focalpoint) && $handle->image_src_x > 0) { $focalpoint = explode('#', $item->focalpoint); $crop = array('top' => 0, 'right' => 0, 'bottom' => 0, 'left' => 0); // calculate how the file will be scaled, by width or by height if ($handle->image_src_x / $handle->image_x > $handle->image_src_y / $handle->image_y) { // Y is ok, now crop extra space on X $ratio = $handle->image_y / $handle->image_src_y; $image_scaled_x = intval($handle->image_src_x * $ratio); $crop['left'] = max(0, round(($image_scaled_x * ($focalpoint[1] / 100) - $handle->image_x / 2) / $ratio)); $crop['right'] = max(0, round(($image_scaled_x * ((100 - $focalpoint[1]) / 100) - $handle->image_x / 2) / $ratio)); } else { // X is ok, now crop extra space on Y $ratio = $handle->image_x / $handle->image_src_x; $image_scaled_y = intval($handle->image_src_y * $ratio); $crop['top'] = max(0, round(($image_scaled_y * ($focalpoint[0] / 100) - $handle->image_y / 2) / $ratio)); $crop['bottom'] = max(0, round(($image_scaled_y * ((100 - $focalpoint[0]) / 100) - $handle->image_y / 2) / $ratio)); } $handle->image_precrop = array($crop['top'], $crop['right'], $crop['bottom'], $crop['left']); } $handle->image_ratio_crop = true; $handle->image_ratio_fill = true; } $handle->png_compression = 9; $handle->process(dirname($thumbnail)); rename($handle->file_dst_pathname, $thumbnail); clearstatcache(true, $thumbnail); if (!file_exists($thumbnail) || filesize($thumbnail) < 1) { return NULL; } // try to recompress the png thumbnail file to achieve the minimum file size, // only if some extra apps are available if (extension_loaded('imagick')) { $im = new Imagick($thumbnail); $image_alpha_range = $im->getImageChannelRange(Imagick::CHANNEL_ALPHA); //$image_alpha_mean = $im->getImageChannelMean(Imagick::CHANNEL_ALPHA); $image_is_opaque = $image_alpha_range['minima'] == 0 && $image_alpha_range['maxima'] == 0; // autorotate image based on EXIF data $im_original = new Imagick($original); $orientation = $im_original->getImageOrientation(); $im_original->clear(); switch ($orientation) { case imagick::ORIENTATION_BOTTOMRIGHT: $im->rotateimage(new ImagickPixel('transparent'), 180); // rotate 180 degrees break; case imagick::ORIENTATION_RIGHTTOP: $im->rotateimage(new ImagickPixel('transparent'), 90); // rotate 90 degrees CW break; case imagick::ORIENTATION_LEFTBOTTOM: $im->rotateimage(new ImagickPixel('transparent'), -90); // rotate 90 degrees CCW break; } // Now that it's auto-rotated, make sure the EXIF data is correct in case the EXIF gets saved with the image! $im->setImageOrientation(imagick::ORIENTATION_TOPLEFT); if (!$image_is_opaque) { $im->setImageFormat('PNG32'); // Force a full RGBA image format with full semi-transparency. $im->setBackgroundColor(new ImagickPixel('transparent')); $im->setImageCompression(Imagick::COMPRESSION_UNDEFINED); $im->setImageCompressionQuality(0); $im->writeimage($thumbnail); } else { $im->setImageFormat('JPG'); // create an OPAQUE JPG file with the given quality (default 95%) $im->setImageCompressionQuality($quality); $im->writeimage($thumbnail_path_jpg); @unlink($thumbnail); $thumbnail = $thumbnail_path_jpg; } } /* if(command_exists('pngquant')) // PNG Optimization: 8 bit with transparency { @shell_exec('pngquant -s1 --ext .pngquant '.$thumbnail); if(file_exists($thumbnail.'.pngquant')) { unlink($thumbnail); rename($thumbnail.'.pngquant', $thumbnail); } } else*/ } clearstatcache(true, $thumbnail); return $thumbnail; }
function defaultText($o) { if ($o['case'] == 'upper') { $o['text'] = strtoupper($o['text']); } global $gravities, $fonts; $text = new Imagick(); $text->setFont($fonts[$o['font']]); $text->setBackgroundColor("none"); $text->setGravity($gravities[$o['gravity']]); if ($o['text'] == '') { $text->newPseudoImage($o['w'], $o['h'], "null:"); } else if ($o['wordWrap']) { $text->newPseudoImage($o['w'], $o['h'], "caption:" . $o['text']); } else { $text->newPseudoImage($o['w'], $o['h'], "label:" . $o['text']); } //$metrics = $text->queryFontMetrics( $annotate, $text ); return $text; }
public function getMediaThumbnail(Request $request, Response $response, $arguments) { try { $imagick = new \Imagick(); $imagick->setResolution(144, 144); $imagick->setBackgroundColor('#ffffff'); $imagick->readImage('uploads/' . $arguments['filename'] . '[0]'); $imagick->scaleImage(640, 0); $imagick->cropImage(640, 480, 0, 0); $imagick->setImagePage(0, 0, 0, 0); $imagick = $imagick->flattenImages(); $imagick->setImageFormat('jpeg'); $imageData = $imagick->getImageBlob(); return $response->withHeader('Content-Type', 'image/jpeg')->write($imageData); } catch (\Exception $e) { return $response->withStatus(404); } }
function RightSideImage() { $RightSideImage = new Imagick($this->{$userDp}); $RightSideImage->setImageFormat("png"); $RightSideImage->roundCorners(20, 20); $RightSideImage->resizeImage(160, 200, Imagick::FILTER_LANCZOS, 1); $RightSideImage->setBackgroundColor(new ImagickPixel('transparent')); $RightSideImage->writeImage("RightSideImage.png"); $CreateRightSideImage = imagecreatefrompng("RightSideImage.png"); }
/** * Color blend filter, more advanced version of colorize. * * Code by olav@redwall.ee on http://php.net/manual/en/imagick.colorizeimage.php * * @param $imageInstance * @param $color * @param int $alpha * @param int $composite_flag */ private function _colorBlend($imagickInstance, $color, $alpha = 1, $composite_flag = \Imagick::COMPOSITE_COLORIZE) { $draw = new \ImagickDraw(); $draw->setFillColor($color); $width = $imagickInstance->getImageWidth(); $height = $imagickInstance->getImageHeight(); $draw->rectangle(0, 0, $width, $height); $temporary = new \Imagick(); $temporary->setBackgroundColor(new \ImagickPixel('transparent')); $temporary->newImage($width, $height, new \ImagickPixel('transparent')); $temporary->setImageFormat('png32'); $temporary->drawImage($draw); $alphaChannel = clone $imagickInstance; $alphaChannel->setImageAlphaChannel(\Imagick::ALPHACHANNEL_EXTRACT); $alphaChannel->negateImage(false, \Imagick::CHANNEL_ALL); $imagickInstance->setImageClipMask($alphaChannel); $clone = clone $imagickInstance; $clone->compositeImage($temporary, $composite_flag, 0, 0); $clone->setImageOpacity($alpha); $imagickInstance->compositeImage($clone, \Imagick::COMPOSITE_DEFAULT, 0, 0); }
static function nonImageAddTexte($text, $fontfile, $fontsize) { $svg = '<?xml version="1.0" encoding="utf-8"?> <!-- The icon can be used freely in both personal and commercial projects with no attribution required, but always appreciated. You may NOT sub-license, resell, rent, redistribute or otherwise transfer the icon without express written permission from iconmonstr.com --> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"> <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="512px" height="512px" viewBox="0 0 512 512" xml:space="preserve"> <defs> <linearGradient id="degrade" x1="100%" y1="0" x2="100%" y2="100%"> <stop offset="0%" style="stop-color:#898989; stop-opacity:0.2;"/> <stop offset="40%" style="stop-color:#464646; stop-opacity:1;"/> <stop offset="100%" style="stop-color:#111111; stop-opacity:0.7;"/> </linearGradient> <linearGradient id="degrade1" x1="100%" y1="0" x2="100%" y2="100%"> <stop offset="0%" style="stop-color:#111111; stop-opacity:0.7;"/> <stop offset="40%" style="stop-color:#AAAAAA; stop-opacity:1;"/> <stop offset="100%" style="stop-color:#F0F0F0; stop-opacity:0.2;"/> </linearGradient> <style type="text/css"> #stop1{ stop-color:chartreuse; stop-opacity:0.2; } #stop2{ stop-color:cornflowerblue; stop-opacity:1; } #stop3{ stop-color:chartreuse; stop-opacity:0.7; } </style> </defs> <path style="fill:url(#degrade); stroke:#BBBBBB; stroke-width:2px;" id="video-icon" d="M50,60.345v391.311h412V60.345H50z M137.408,410.862H92.354v-38.747h45.055V410.862z M137.408,343.278 H92.354v-38.747h45.055V343.278z M137.408,275.372H92.354v-38.747h45.055V275.372z M137.408,208.111H92.354v-38.748h45.055V208.111z M137.408,140.526H92.354v-38.747h45.055V140.526z M337.646,410.862H177.961V275.694h159.685V410.862z M337.646,236.947H177.961 V101.779h159.685V236.947z M423.253,410.862h-45.054v-38.747h45.054V410.862z M423.253,343.278h-45.054v-38.747h45.054V343.278z M423.253,275.372h-45.054v-38.747h45.054V275.372z M423.253,208.111h-45.054v-38.748h45.054V208.111z M423.253,140.526h-45.054 v-38.747h45.054V140.526z"/> </svg> '; $im2 = new \Imagick(); $im2->setBackgroundColor(new \ImagickPixel('transparent')); $im2->readimageblob($svg); $im2->setImageFormat("png"); $im2->adaptiveResizeImage(140, 140); /*Optional, if you need to resize*/ //return $im2->getimageblob(); $im = new \Imagick(); $im->newimage(260, 300, new \ImagickPixel('#999999'), "jpeg"); $im->compositeimage($im2, \Imagick::COMPOSITE_DEFAULT, 60, 80); $widthmax = $im->getImageGeometry()["width"]; $draw = new \ImagickDraw(); /* On commence un nouveau masque nommé "gradient" */ $draw->setFillColor('#FFFFFF'); /* Font properties */ $draw->setFont($fontfile); $draw->setFontSize($fontsize); $draw->setGravity(\Imagick::GRAVITY_NORTH); $words = explode(' ', $text); //Test si la fontsize n'est pas trop grosse pour un mot $i = 0; while ($i < count($words)) { $lineSize = $im->queryfontmetrics($draw, $words[$i])["textWidth"]; if ($lineSize < $widthmax) { $i++; } else { $fontsize--; $draw->setFontSize($fontsize); } } $res = $words[0]; for ($i = 1; $i < count($words); $i++) { $lineSize = $im->queryfontmetrics($draw, $res . " " . $words[$i]); if ($lineSize["textWidth"] < $widthmax) { $res .= " " . $words[$i]; } else { $res .= "\n" . $words[$i]; } } /* Create text */ $im->annotateImage($draw, 0, 0, 0, $res); return $im->getimageblob(); }
$FriendDpImage->roundCorners(20, 20); $FriendDpImage->resizeImage(20, 20, Imagick::FILTER_LANCZOS, 1); $FriendDpImage->setBackgroundColor(new ImagickPixel('transparent')); $FriendDpImage->writeImage("rounded.png"); //UserDP $UserDPImage = new Imagick($path); $UserDPImage->setImageFormat("png"); $UserDPImage->roundCorners(20, 20); $UserDPImage->resizeImage(210, 244, Imagick::FILTER_LANCZOS, 1); $UserDPImage->setBackgroundColor(new ImagickPixel('transparent')); $UserDPImage->writeImage("rounded.png"); //HeartImage $HeartImage = new Imagick("images/bk.jpg"); $HeartImage->setImageFormat("png"); $HeartImage->resizeImage(120, 100, Imagick::FILTER_LANCZOS, 1); $HeartImage->setBackgroundColor(new ImagickPixel('transparent')); $HeartImage->writeImage("heart.png"); $top_image1 = imagecreatefrompng("rounded.png"); $top_image2 = imagecreatefrompng("rounded2.png"); $top_image4 = imagecreatefrompng("images/gg.png"); //Path of this to be saved image $merged_image = "dps/{$uid}.png"; imagesavealpha($top_image1, true); imagealphablending($top_image1, true); imagesavealpha($top_image2, true); imagealphablending($top_image2, true); imagecopy($base_image, $top_image2, 280, 23, 0, 0, $width, $height); //right side frame imagecopy($base_image, $top_image1, 40, 23, 0, 0, $width, $height); //Left side photo frame function TextOverlay()
public static function rasterizeImagickExt($srcPath, $dstPath, $width, $height) { $im = new Imagick($srcPath); $im->setImageFormat('png'); $im->setBackgroundColor('transparent'); $im->setImageDepth(8); if (!$im->thumbnailImage(intval($width), intval($height), false)) { return 'Could not resize image'; } if (!$im->writeImage($dstPath)) { return "Could not write to {$dstPath}"; } }
function thumbnailImage($imagePath) { $im = new Imagick(); $im->setBackgroundColor(new ImagickPixel('transparent')); $im->readImage(realpath($imagePath)); $dim = $im->getImageGeometry(); if (!isset($_GET['wh'])) { $wh = 100; } $wh = intval($_GET['wh']); if ($wh <= 0) { $wh = 100; } // $aspect=floatval($dim['width'])/floatval($dim['height']); // $inverse_aspect=floatval($dim['height'])/floatval($dim['width']); $width = $wh; $height = $wh; $im->setImageFormat("png32"); $im->thumbnailImage($width, $height, true, true); header("Content-Type: image/png"); echo $im; }
function gradientDown($width, $height) { $imagick = new Imagick(); $imagick->setBackgroundColor('yellow'); $imagick->newPseudoImage($width, $height, 'gradient:white-black'); return $imagick; }