/** * {@inheritdoc} */ public function current() { if (!isset($this->layers[$this->offset])) { try { $this->resource->setIteratorIndex($this->offset); $this->layers[$this->offset] = $this->resource->getImage(); } catch (\GmagickException $e) { throw new RuntimeException(sprintf('Failed to extract layer %d', $this->offset), $e->getCode(), $e); } } return new Image($this->layers[$this->offset]); }
/** * Loads image from $this->file into new Imagick Object. * * @since 3.5.0 * @access protected * * @return true|WP_Error True if loaded; WP_Error on failure. */ public function load() { if ($this->image instanceof Imagick) { return true; } if (!is_file($this->file) && !preg_match('|^https?://|', $this->file)) { return new WP_Error('error_loading_image', __('File doesn’t exist?'), $this->file); } /** This filter is documented in wp-includes/class-wp-image-editor-imagick.php */ // Even though Imagick uses less PHP memory than GD, set higher limit for users that have low PHP.ini limits @ini_set('memory_limit', apply_filters('image_memory_limit', WP_MAX_MEMORY_LIMIT)); try { $this->image = new Imagick($this->file); if (!$this->image->valid()) { return new WP_Error('invalid_image', __('File is not an image.'), $this->file); } // Select the first frame to handle animated images properly if (is_callable(array($this->image, 'setIteratorIndex'))) { $this->image->setIteratorIndex(0); } $this->mime_type = $this->get_mime_type($this->image->getImageFormat()); } catch (Exception $e) { return new WP_Error('invalid_image', $e->getMessage(), $this->file); } $updated_size = $this->update_size(); if (is_wp_error($updated_size)) { return $updated_size; } return $this->set_quality(); }
/** * Create a image from a non image file content. (Ex. PDF, PSD or TIFF) * * @param $content * @param string $format * * @return bool|string */ public static function createImageFromNonImage($content, $format = 'jpeg') { if (!extension_loaded('imagick')) { return false; } $image = new \Imagick(); $image->readImageBlob($content); $image->setIteratorIndex(0); $image->setImageFormat($format); return $image->getImageBlob(); }
/** * Request a specific image from the collection of images. * * @param integer $index The index to return * * @return Horde_Image_Base */ public function getImageAtIndex($index) { if ($index >= $this->_imagick->getNumberImages()) { throw Horde_Image_Exception('Image index out of bounds.'); } $currentIndex = $this->_imagick->getIteratorIndex(); $this->_imagick->setIteratorIndex($index); $image = $this->current(); $this->_imagick->setIteratorIndex($currentIndex); return $image; }
/** * {@inheritdoc} */ public function getSize() { try { $i = $this->imagick->getIteratorIndex(); $this->imagick->rewind(); $width = $this->imagick->getImageWidth(); $height = $this->imagick->getImageHeight(); $this->imagick->setIteratorIndex($i); } catch (\ImagickException $e) { throw new RuntimeException('Could not get size', $e->getCode(), $e); } return new Box($width, $height); }
/** * {@inheritdoc} */ public function offsetUnset($offset) { try { $this->extractAt($offset); } catch (RuntimeException $e) { return; } try { $this->resource->setIteratorIndex($offset); $this->resource->removeImage(); } catch (\ImagickException $e) { throw new RuntimeException('Unable to remove layer', $e->getCode(), $e); } }
/** * Loads image from $this->file into new Imagick Object. * * @since 3.5.0 * @access protected * * @return true|WP_Error True if loaded; WP_Error on failure. */ public function load() { if ($this->image instanceof Imagick) { return true; } if (!is_file($this->file) && !preg_match('|^https?://|', $this->file)) { return new WP_Error('error_loading_image', __('File doesn’t exist?'), $this->file); } /* * Even though Imagick uses less PHP memory than GD, set higher limit * for users that have low PHP.ini limits. */ wp_raise_memory_limit('image'); try { $this->image = new Imagick(); $file_parts = pathinfo($this->file); $filename = $this->file; // By default, PDFs are rendered in a very low resolution. // We want the thumbnail to be readable, so increase the rendering dpi. if ('pdf' == strtolower($file_parts['extension'])) { $this->image->setResolution(128, 128); // Only load the first page. $filename .= '[0]'; } // Reading image after Imagick instantiation because `setResolution` // only applies correctly before the image is read. $this->image->readImage($filename); if (!$this->image->valid()) { return new WP_Error('invalid_image', __('File is not an image.'), $this->file); } // Select the first frame to handle animated images properly if (is_callable(array($this->image, 'setIteratorIndex'))) { $this->image->setIteratorIndex(0); } $this->mime_type = $this->get_mime_type($this->image->getImageFormat()); } catch (Exception $e) { return new WP_Error('invalid_image', $e->getMessage(), $this->file); } $updated_size = $this->update_size(); if (is_wp_error($updated_size)) { return $updated_size; } return $this->set_quality(); }
/** * {@inheritdoc} */ public function createVariation(ImageFormat $output_format, $quality, ImageDimensions $dimensions = null, ImageCropDimensions $crop_dimensions = null) { $src = $this->getTempFile($this->data); $img = new \Imagick(); $img->setResolution($this->resolution, $this->resolution); $img->readImage($src); $img->setIteratorIndex(0); // Flatten images here helps the encoder to get rid of the black background // that appears on encoded image files. $img = $img->flattenImages(); $img->setImageFormat((string) $output_format->value()); $img->setImageCompressionQuality($quality); if (null !== $crop_dimensions) { $img->cropImage($crop_dimensions->getWidth(), $crop_dimensions->getHeight(), $crop_dimensions->getX(), $crop_dimensions->getY()); } if (null !== $dimensions) { $img->resizeImage($dimensions->getWidth() ?: 0, $dimensions->getHeight() ?: 0, $this->filter, 1, false); } return $img->getImageBlob(); }
/** * Loads image from $this->file into new Imagick Object. * * @since 3.5.0 * @access protected * * @return true|WP_Error True if loaded; WP_Error on failure. */ public function load() { if ($this->image instanceof Imagick) { return true; } if (!is_file($this->file) && !preg_match('|^https?://|', $this->file)) { return new WP_Error('error_loading_image', __('File doesn’t exist?'), $this->file); } /* * Even though Imagick uses less PHP memory than GD, set higher limit * for users that have low PHP.ini limits. */ wp_raise_memory_limit('image'); try { $this->image = new Imagick(); $file_extension = strtolower(pathinfo($this->file, PATHINFO_EXTENSION)); $filename = $this->file; if ('pdf' == $file_extension) { $filename = $this->pdf_setup(); } // Reading image after Imagick instantiation because `setResolution` // only applies correctly before the image is read. $this->image->readImage($filename); if (!$this->image->valid()) { return new WP_Error('invalid_image', __('File is not an image.'), $this->file); } // Select the first frame to handle animated images properly if (is_callable(array($this->image, 'setIteratorIndex'))) { $this->image->setIteratorIndex(0); } $this->mime_type = $this->get_mime_type($this->image->getImageFormat()); } catch (Exception $e) { return new WP_Error('invalid_image', $e->getMessage(), $this->file); } $updated_size = $this->update_size(); if (is_wp_error($updated_size)) { return $updated_size; } return $this->set_quality(); }
private function make_thumbnail_Imagick($src_path, $width, $height, $dest) { $image = new Imagick($src_path); # Select the first frame to handle animated images properly if (is_callable(array($image, 'setIteratorIndex'))) { $image->setIteratorIndex(0); } // устанавливаем качество $format = $image->getImageFormat(); if ($format == 'JPEG' || $format == 'JPG') { $image->setImageCompression(Imagick::COMPRESSION_JPEG); } $image->setImageCompressionQuality(85); $h = $image->getImageHeight(); $w = $image->getImageWidth(); // если не указана одна из сторон задаем ей пропорциональное значение if (!$width) { $width = round($w * ($height / $h)); } if (!$height) { $height = round($h * ($width / $w)); } list($dx, $dy, $wsrc, $hsrc) = $this->crop_coordinates($height, $h, $width, $w); // обрезаем оригинал $image->cropImage($wsrc, $hsrc, $dx, $dy); $image->setImagePage($wsrc, $hsrc, 0, 0); // Strip out unneeded meta data $image->stripImage(); // уменьшаем под размер $image->scaleImage($width, $height); $image->writeImage($dest); chmod($dest, 0755); $image->clear(); $image->destroy(); return true; }
/** * Load a PDF for use on the printer * * @param string $pdfFile The file to load * @param string $pageWidth The width, in pixels, of the printer's output. The first page of the PDF will be scaled to approximately fit in this area. * @param array $range array indicating the first and last page (starting from 0) to load. If not set, the entire document is loaded. * @throws Exception Where Imagick is not loaded, or where a missing file or invalid page number is requested. * @return multitype:EscposImage Array of images, retrieved from the PDF file. */ public static function loadPdf($pdfFile, $pageWidth = 550) { if (!extension_loaded('imagick')) { throw new Exception(__FUNCTION__ . " requires imagick extension."); } /* * Load first page at very low density (resolution), to figure out what * density to use to achieve $pageWidth */ try { $image = new \Imagick(); $testRes = 2; // Test resolution $image->setresolution($testRes, $testRes); /* Load document just to measure geometry */ $image->readimage($pdfFile); $geo = $image->getimagegeometry(); $image->destroy(); $width = $geo['width']; $newRes = $pageWidth / $width * $testRes; /* Load entire document in */ $image->setresolution($newRes, $newRes); $image->readImage($pdfFile); $pages = $image->getNumberImages(); /* Convert images to Escpos objects */ $ret = array(); for ($i = 0; $i < $pages; $i++) { $image->setIteratorIndex($i); $ep = new EscposImage(); $ep->readImageFromImagick($image); $ret[] = $ep; } return $ret; } catch (\ImagickException $e) { // Wrap in normal exception, so that classes which call this do not themselves require imagick as a dependency. throw new Exception($e); } }
private function generate_adobe_thumb($working_dir, $input_filename, $output_filename) { $pos = strrpos($input_filename, "."); $input_extension = substr($input_filename, $pos + 1); $input_path = $working_dir . "/{$input_filename}"; $output_extension = "png"; $image = new Imagick($input_path); $image->setResolution(300, 300); $image->setImageFormat($output_extension); if ($input_extension == "psd") { $image->setIteratorIndex(0); } $success = $image->writeImage($working_dir . "/{$output_filename}"); return $success; }
<?php // error_reporting(E_ERROR | E_WARNING); $im = new Imagick('logo.psd'); $im->setImageIndex(0); $im->setIteratorIndex(0); $im->stripImage(); //去除图片信息 $im->setImageCompressionQuality(80); //图片质量 $im->writeImage('logo.jpg'); echo "<img src='logo.jpg'/>";
public static function generateThumbnail($localPath, $format, $thumbnailSize, $cropEnabled) { switch ($format) { case 'jpg': case 'jpeg': // $img = imagecreatefromjpeg($localPath); $img = imagecreatefromstring($localPath); break; case 'gif': // $img = imagecreatefromgif($localPath); $img = imagecreatefromstring($localPath); break; case 'png': // $img = imagecreatefrompng($localPath); $img = imagecreatefromstring($localPath); break; case 'pdf': case 'psd': case 'tif': case 'tiff': case 'svg': if (extension_loaded('imagick')) { $image = new \Imagick(); $image->readImageBlob($localPath); $image->setIteratorIndex(0); $image->setImageFormat('jpeg'); $img = $image->getImageBlob(); } else { return false; } break; default: return false; } $w = imagesx($img); $h = imagesy($img); $x1 = 0; // used for crops $y1 = 0; // used for crops $aspectRatio = $w / $h; if ($cropEnabled) { // crop to center of image if ($aspectRatio <= 1) { $newW = $thumbnailSize; $newH = $h * ($thumbnailSize / $w); $y1 = -1 * (($newH - $thumbnailSize) / 2); } else { $newH = $thumbnailSize; $newW = $w * ($thumbnailSize / $h); $x1 = -1 * (($newW - $thumbnailSize) / 2); } } else { // portrait (or square) mode, maximize height if ($aspectRatio <= 1) { $newH = $thumbnailSize; $newW = $thumbnailSize * $aspectRatio; } // landscape mode, maximize width if ($aspectRatio > 1) { $newW = $thumbnailSize; $newH = $thumbnailSize / $aspectRatio; } } if ($cropEnabled) { $imgResized = imagecreatetruecolor($thumbnailSize, $thumbnailSize); } else { $imgResized = imagecreatetruecolor($newW, $newH); } // Preserve transperancy for gifs and pngs if ($format == 'gif' || $format == 'png') { imagealphablending($imgResized, false); imagesavealpha($imgResized, true); $transparent = imagecolorallocatealpha($imgResized, 255, 255, 255, 127); imagefilledrectangle($imgResized, 0, 0, $newW, $newH, $transparent); } imagecopyresampled($imgResized, $img, $x1, $y1, 0, 0, $newW, $newH, $w, $h); imagedestroy($img); return $imgResized; }
protected function _reflection($height, $opacity, $fade_in) { if ($this->_version >= 30100) { $reflection = clone $this->_image; } else { $reflection = clone $this->_image->{$clone}(); } $reflection->setIteratorIndex(0); while (true) { $reflection->flipImage(); $reflection->cropImage($reflection->getImageWidth(), $height, 0, 0); $reflection->setImagePage($reflection->getImageWidth(), $height, 0, 0); if (!$reflection->nextImage()) { break; } } $pseudo = $fade_in ? "gradient:black-transparent" : "gradient:transparent-black"; $fade = new \Imagick(); $fade->newPseudoImage($reflection->getImageWidth(), $reflection->getImageHeight(), $pseudo); $opacity /= 100; $reflection->setIteratorIndex(0); while (true) { $reflection->compositeImage($fade, constant("Imagick::COMPOSITE_DSTOUT"), 0, 0); $reflection->evaluateImage(constant("Imagick::EVALUATE_MULTIPLY"), $opacity / 100, constant("Imagick::CHANNEL_ALPHA")); if (!$reflection->nextImage()) { break; } } $fade->destroy(); $image = new \Imagick(); $pixel = new \ImagickPixel(); $height = $this->_image->getImageHeight() + $height; $this->_image->setIteratorIndex(0); while (true) { $image->newImage($this->_width, $height, $pixel); $image->setImageAlphaChannel(constant("Imagick::ALPHACHANNEL_SET")); $image->setColorspace($this->_image->getColorspace()); $image->setImageDelay($this->_image->getImageDelay()); $image->compositeImage($this->_image, constant("Imagick::COMPOSITE_SRC"), 0, 0); if (!$this->_image->nextImage()) { break; } } $image->setIteratorIndex(0); $reflection->setIteratorIndex(0); while (true) { $image->compositeImage($reflection, constant("Imagick::COMPOSITE_OVER"), 0, $this->_height); $image->setImageAlphaChannel(constant("Imagick::ALPHACHANNEL_SET")); $image->setColorspace($this->_image->getColorspace()); $image->setImageDelay($this->_image->getImageDelay()); $image->compositeImage($this->_image, constant("Imagick::COMPOSITE_SRC"), 0, 0); if (!$image->nextImage() || !$reflection->nextImage()) { break; } } $reflection->destroy(); $this->_image->clear(); $this->_image->destroy(); $this->_image = $image; $this->_width = $this->_image->getImageWidth(); $this->_height = $this->_image->getImageHeight(); }
private function extractPages() { // Nome base para os ficheiros extraídos $basename = $this->basedir . '/' . pathinfo($this->filename)['filename'] . '-PDF-%03d.png'; $this->logger->info('Basename: ' . $basename); $im = new \Imagick(); //$im->setResolution(300, 300); $im->setResolution(150, 150); //$im->setResolution(200, 200); $im->readImageBlob(file_get_contents($this->filename)); $this->logger->info('Cargando: ' . $this->filename); $num_pages = $im->getNumberImages(); $this->logger->info('Total enquisas a procesar: ' . $num_pages); $pages = array(); for ($i = 0; $i < $num_pages; $i++) { $im->setIteratorIndex($i); $im->setImageFormat('png'); $filename = sprintf($basename, $i); $this->logger->info('Gardando...: ' . $filename); $im->writeImage($filename); $this->logger->info('Imaxe da enquisa ' . $i . '/' . $num_pages . ' gardada en ' . $filename); $pages[] = $filename; } $im->destroy(); return $pages; }
/** * compute a thumbnail image for a file * * This function builds a preview image where possible, and returns its URL to caller, or NULL. * That result can be saved directly as attribute ##thumbnail_url## or associated file record. * * @param string path to the file, including trailing slash (e.g., 'files/article/123/') * @param string file name (e.g., 'document.pdf') * @return string web address of the thumbnail that has been built, or NULL * * @see files/edit.php */ public static function derive_thumbnail($file_path, $file_name) { global $context; // if the file is an image, create a thumbnail for it if (($image_information = Safe::GetImageSize($file_path . $file_name)) && $image_information[2] >= 1 && $image_information[2] <= 3) { // derive a thumbnail image $thumbnail_name = 'thumbs/' . $file_name; include_once $context['path_to_root'] . 'images/image.php'; Image::shrink($context['path_to_root'] . $file_path . $file_name, $context['path_to_root'] . $file_path . $thumbnail_name, FALSE, TRUE); // remember the address of the thumbnail return $context['url_to_root'] . $file_path . $thumbnail_name; // if this is a PDF that can be converted by Image Magick, then compute a thumbnail for the file } else { if (preg_match('/\\.pdf$/i', $file_name) && class_exists('Imagick') && ($handle = new Imagick($context['path_to_root'] . $file_path . $file_name))) { // derive a thumbnail image $thumbnail_name = 'thumbs/' . $file_name . '.png'; Safe::mkdir($context['path_to_root'] . $file_path . 'thumbs'); // consider only the first page $handle->setIteratorIndex(0); $handle->setImageCompression(Imagick::COMPRESSION_LZW); $handle->setImageCompressionQuality(90); $handle->stripImage(90); $handle->thumbnailImage(100, NULL); $handle->writeImage($context['path_to_root'] . $file_path . $thumbnail_name); // remember the address of the thumbnail return $context['url_to_root'] . $file_path . $thumbnail_name; } } // no thumbnail return NULL; }
/** * Load a PDF for use on the printer * * @param string $pdfFile The file to load * @param string $pageWidth The width, in pixels, of the printer's output. The first page of the PDF will be scaled to approximately fit in this area. * @param array $range array indicating the first and last page (starting from 0) to load. If not set, the entire document is loaded. * @throws Exception Where Imagick is not loaded, or where a missing file or invalid page number is requested. * @return multitype:EscposImage Array of images, retrieved from the PDF file. */ public static function loadPdf($pdfFile, $pageWidth = 550, array $range = null) { if (!extension_loaded('imagick')) { throw new Exception(__FUNCTION__ . " requires imagick extension."); } /* * Load first page at very low density (resolution), to figure out what * density to use to achieve $pageWidth */ try { $image = new Imagick(); $testRes = 2; // Test resolution $image->setresolution($testRes, $testRes); $image->readimage($pdfFile . "[0]"); $geo = $image->getimagegeometry(); $image->destroy(); $width = $geo['width']; $newRes = $pageWidth / $width * $testRes; /* Load actual document (can be very slow!) */ $rangeStr = ""; // Set to [0] [0-1] page range if $range is set if ($range != null) { if (count($range) != 2 || !isset($range[0]) || !is_integer($range[0]) || !isset($range[1]) || !is_integer($range[1]) || $range[0] > $range[1]) { throw new Exception("Invalid range. Must be two numbers in the array: The start and finish page indexes, starting from 0."); } $rangeStr = "[" . ($range[0] == $range[1] ? $range[0] : implode($range, "-")) . "]"; } $image->setresolution($newRes, $newRes); $image->readImage($pdfFile . "{$rangeStr}"); $pages = $image->getNumberImages(); /* Convert images to Escpos objects */ $ret = array(); for ($i = 0; $i < $pages; $i++) { $image->setIteratorIndex($i); $ep = new EscposImage(); $ep->readImageFromImagick($image); $ret[] = $ep; } return $ret; } catch (ImagickException $e) { // Wrap in normal exception, so that classes which call this do not themselves require imagick as a dependency. throw new Exception($e); } }
public function getPreview($new_w = 200, $new_h = 200) { if ($this->hasPreview() && file_exists($this->getFullURI())) { $image = new Imagick($this->getFullURI()); if ($this->getMimeType() == 'application/pdf') { // Display page 1 of pdfs $image->setIteratorIndex(0); } $image->thumbnailImage($new_w, $new_h, true); $image->setImageFormat("png"); $image->setCompression(Imagick::COMPRESSION_LZW); $image->setCompressionQuality(90); return $image->getImageBlob(); } }