3 * WordPress Imagick Image Editor
6 * @subpackage Image_Editor
10 * WordPress Image Editor Class for Image Manipulation through Imagick PHP Module
14 * @subpackage Image_Editor
15 * @uses WP_Image_Editor Extends class
17 class WP_Image_Editor_Imagick extends WP_Image_Editor {
26 public function __destruct() {
27 if ( $this->image instanceof Imagick ) {
28 // we don't need the original in memory anymore
29 $this->image->clear();
30 $this->image->destroy();
35 * Checks to see if current environment supports Imagick.
37 * We require Imagick 2.2.0 or greater, based on whether the queryFormats()
38 * method can be called statically.
48 public static function test( $args = array() ) {
50 // First, test Imagick's extension and classes.
51 if ( ! extension_loaded( 'imagick' ) || ! class_exists( 'Imagick', false ) || ! class_exists( 'ImagickPixel', false ) )
54 if ( version_compare( phpversion( 'imagick' ), '2.2.0', '<' ) )
57 $required_methods = array(
67 'setimagecompression',
68 'setimagecompressionquality',
78 // Now, test for deep requirements within Imagick.
79 if ( ! defined( 'imagick::COMPRESSION_JPEG' ) )
82 $class_methods = array_map( 'strtolower', get_class_methods( 'Imagick' ) );
83 if ( array_diff( $required_methods, $class_methods ) ) {
87 // HHVM Imagick does not support loading from URL, so fail to allow fallback to GD.
88 if ( defined( 'HHVM_VERSION' ) && isset( $args['path'] ) && preg_match( '|^https?://|', $args['path'] ) ) {
96 * Checks to see if editor supports the mime-type specified.
103 * @param string $mime_type
106 public static function supports_mime_type( $mime_type ) {
107 $imagick_extension = strtoupper( self::get_extension( $mime_type ) );
109 if ( ! $imagick_extension )
112 // setIteratorIndex is optional unless mime is an animated format.
113 // Here, we just say no if you are missing it and aren't loading a jpeg.
114 if ( ! method_exists( 'Imagick', 'setIteratorIndex' ) && $mime_type != 'image/jpeg' )
118 return ( (bool) @Imagick::queryFormats( $imagick_extension ) );
120 catch ( Exception $e ) {
126 * Loads image from $this->file into new Imagick Object.
131 * @return true|WP_Error True if loaded; WP_Error on failure.
133 public function load() {
134 if ( $this->image instanceof Imagick )
137 if ( ! is_file( $this->file ) && ! preg_match( '|^https?://|', $this->file ) )
138 return new WP_Error( 'error_loading_image', __('File doesn’t exist?'), $this->file );
140 /** This filter is documented in wp-includes/class-wp-image-editor-imagick.php */
141 // Even though Imagick uses less PHP memory than GD, set higher limit for users that have low PHP.ini limits
142 @ini_set( 'memory_limit', apply_filters( 'image_memory_limit', WP_MAX_MEMORY_LIMIT ) );
145 $this->image = new Imagick( $this->file );
147 if ( ! $this->image->valid() )
148 return new WP_Error( 'invalid_image', __('File is not an image.'), $this->file);
150 // Select the first frame to handle animated images properly
151 if ( is_callable( array( $this->image, 'setIteratorIndex' ) ) )
152 $this->image->setIteratorIndex(0);
154 $this->mime_type = $this->get_mime_type( $this->image->getImageFormat() );
156 catch ( Exception $e ) {
157 return new WP_Error( 'invalid_image', $e->getMessage(), $this->file );
160 $updated_size = $this->update_size();
161 if ( is_wp_error( $updated_size ) ) {
162 return $updated_size;
165 return $this->set_quality();
169 * Sets Image Compression quality on a 1-100% scale.
174 * @param int $quality Compression Quality. Range: [1,100]
175 * @return true|WP_Error True if set successfully; WP_Error on failure.
177 public function set_quality( $quality = null ) {
178 $quality_result = parent::set_quality( $quality );
179 if ( is_wp_error( $quality_result ) ) {
180 return $quality_result;
182 $quality = $this->get_quality();
186 if ( 'image/jpeg' == $this->mime_type ) {
187 $this->image->setImageCompressionQuality( $quality );
188 $this->image->setImageCompression( imagick::COMPRESSION_JPEG );
191 $this->image->setImageCompressionQuality( $quality );
194 catch ( Exception $e ) {
195 return new WP_Error( 'image_quality_error', $e->getMessage() );
202 * Sets or updates current image size.
210 * @return true|WP_Error
212 protected function update_size( $width = null, $height = null ) {
214 if ( !$width || !$height ) {
216 $size = $this->image->getImageGeometry();
218 catch ( Exception $e ) {
219 return new WP_Error( 'invalid_image', __( 'Could not read image size.' ), $this->file );
224 $width = $size['width'];
227 $height = $size['height'];
229 return parent::update_size( $width, $height );
233 * Resizes current image.
235 * At minimum, either a height or width must be provided.
236 * If one of the two is set to null, the resize will
237 * maintain aspect ratio according to the provided dimension.
242 * @param int|null $max_w Image width.
243 * @param int|null $max_h Image height.
245 * @return bool|WP_Error
247 public function resize( $max_w, $max_h, $crop = false ) {
248 if ( ( $this->size['width'] == $max_w ) && ( $this->size['height'] == $max_h ) )
251 $dims = image_resize_dimensions( $this->size['width'], $this->size['height'], $max_w, $max_h, $crop );
253 return new WP_Error( 'error_getting_dimensions', __('Could not calculate resized image dimensions') );
254 list( $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h ) = $dims;
257 return $this->crop( $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h );
260 // Execute the resize
261 $thumb_result = $this->thumbnail_image( $dst_w, $dst_h );
262 if ( is_wp_error( $thumb_result ) ) {
263 return $thumb_result;
266 return $this->update_size( $dst_w, $dst_h );
270 * Efficiently resize the current image
272 * This is a WordPress specific implementation of Imagick::thumbnailImage(),
273 * which resizes an image to given dimensions and removes any associated profiles.
278 * @param int $dst_w The destination width.
279 * @param int $dst_h The destination height.
280 * @param string $filter_name Optional. The Imagick filter to use when resizing. Default 'FILTER_TRIANGLE'.
281 * @param bool $strip_meta Optional. Strip all profiles, excluding color profiles, from the image. Default true.
282 * @return bool|WP_Error
284 protected function thumbnail_image( $dst_w, $dst_h, $filter_name = 'FILTER_TRIANGLE', $strip_meta = true ) {
285 $allowed_filters = array(
304 * Set the filter value if '$filter_name' name is in our whitelist and the related
305 * Imagick constant is defined or fall back to our default filter.
307 if ( in_array( $filter_name, $allowed_filters ) && defined( 'Imagick::' . $filter_name ) ) {
308 $filter = constant( 'Imagick::' . $filter_name );
310 $filter = defined( 'Imagick::FILTER_TRIANGLE' ) ? Imagick::FILTER_TRIANGLE : false;
314 * Filter whether to strip metadata from images when they're resized.
316 * This filter only applies when resizing using the Imagick editor since GD
317 * always strips profiles by default.
321 * @param bool $strip_meta Whether to strip image metadata during resizing. Default true.
323 if ( apply_filters( 'image_strip_meta', $strip_meta ) ) {
324 $this->strip_meta(); // Fail silently if not supported.
329 * To be more efficient, resample large images to 5x the destination size before resizing
330 * whenever the output size is less that 1/3 of the original image size (1/3^2 ~= .111),
331 * unless we would be resampling to a scale smaller than 128x128.
333 if ( is_callable( array( $this->image, 'sampleImage' ) ) ) {
334 $resize_ratio = ( $dst_w / $this->size['width'] ) * ( $dst_h / $this->size['height'] );
337 if ( $resize_ratio < .111 && ( $dst_w * $sample_factor > 128 && $dst_h * $sample_factor > 128 ) ) {
338 $this->image->sampleImage( $dst_w * $sample_factor, $dst_h * $sample_factor );
343 * Use resizeImage() when it's available and a valid filter value is set.
344 * Otherwise, fall back to the scaleImage() method for resizing, which
345 * results in better image quality over resizeImage() with default filter
346 * settings and retains backwards compatibility with pre 4.5 functionality.
348 if ( is_callable( array( $this->image, 'resizeImage' ) ) && $filter ) {
349 $this->image->setOption( 'filter:support', '2.0' );
350 $this->image->resizeImage( $dst_w, $dst_h, $filter, 1 );
352 $this->image->scaleImage( $dst_w, $dst_h );
355 // Set appropriate quality settings after resizing.
356 if ( 'image/jpeg' == $this->mime_type ) {
357 if ( is_callable( array( $this->image, 'unsharpMaskImage' ) ) ) {
358 $this->image->unsharpMaskImage( 0.25, 0.25, 8, 0.065 );
361 $this->image->setOption( 'jpeg:fancy-upsampling', 'off' );
364 if ( 'image/png' === $this->mime_type ) {
365 $this->image->setOption( 'png:compression-filter', '5' );
366 $this->image->setOption( 'png:compression-level', '9' );
367 $this->image->setOption( 'png:compression-strategy', '1' );
368 $this->image->setOption( 'png:exclude-chunk', 'all' );
372 * If alpha channel is not defined, set it opaque.
374 * Note that Imagick::getImageAlphaChannel() is only available if Imagick
375 * has been compiled against ImageMagick version 6.4.0 or newer.
377 if ( is_callable( array( $this->image, 'getImageAlphaChannel' ) )
378 && is_callable( array( $this->image, 'setImageAlphaChannel' ) )
379 && defined( 'Imagick::ALPHACHANNEL_UNDEFINED' )
380 && defined( 'Imagick::ALPHACHANNEL_OPAQUE' )
382 if ( $this->image->getImageAlphaChannel() === Imagick::ALPHACHANNEL_UNDEFINED ) {
383 $this->image->setImageAlphaChannel( Imagick::ALPHACHANNEL_OPAQUE );
387 // Limit the bit depth of resized images to 8 bits per channel.
388 if ( is_callable( array( $this->image, 'getImageDepth' ) ) && is_callable( array( $this->image, 'setImageDepth' ) ) ) {
389 if ( 8 < $this->image->getImageDepth() ) {
390 $this->image->setImageDepth( 8 );
394 if ( is_callable( array( $this->image, 'setInterlaceScheme' ) ) && defined( 'Imagick::INTERLACE_NO' ) ) {
395 $this->image->setInterlaceScheme( Imagick::INTERLACE_NO );
399 catch ( Exception $e ) {
400 return new WP_Error( 'image_resize_error', $e->getMessage() );
405 * Resize multiple images from a single source.
410 * @param array $sizes {
411 * An array of image size arrays. Default sizes are 'small', 'medium', 'medium_large', 'large'.
413 * Either a height or width must be provided.
414 * If one of the two is set to null, the resize will
415 * maintain aspect ratio according to the provided dimension.
417 * @type array $size {
418 * Array of height, width values, and whether to crop.
420 * @type int $width Image width. Optional if `$height` is specified.
421 * @type int $height Image height. Optional if `$width` is specified.
422 * @type bool $crop Optional. Whether to crop the image. Default false.
425 * @return array An array of resized images' metadata by size.
427 public function multi_resize( $sizes ) {
429 $orig_size = $this->size;
430 $orig_image = $this->image->getImage();
432 foreach ( $sizes as $size => $size_data ) {
433 if ( ! $this->image )
434 $this->image = $orig_image->getImage();
436 if ( ! isset( $size_data['width'] ) && ! isset( $size_data['height'] ) ) {
440 if ( ! isset( $size_data['width'] ) ) {
441 $size_data['width'] = null;
443 if ( ! isset( $size_data['height'] ) ) {
444 $size_data['height'] = null;
447 if ( ! isset( $size_data['crop'] ) ) {
448 $size_data['crop'] = false;
451 $resize_result = $this->resize( $size_data['width'], $size_data['height'], $size_data['crop'] );
452 $duplicate = ( ( $orig_size['width'] == $size_data['width'] ) && ( $orig_size['height'] == $size_data['height'] ) );
454 if ( ! is_wp_error( $resize_result ) && ! $duplicate ) {
455 $resized = $this->_save( $this->image );
457 $this->image->clear();
458 $this->image->destroy();
461 if ( ! is_wp_error( $resized ) && $resized ) {
462 unset( $resized['path'] );
463 $metadata[$size] = $resized;
467 $this->size = $orig_size;
470 $this->image = $orig_image;
481 * @param int $src_x The start x position to crop from.
482 * @param int $src_y The start y position to crop from.
483 * @param int $src_w The width to crop.
484 * @param int $src_h The height to crop.
485 * @param int $dst_w Optional. The destination width.
486 * @param int $dst_h Optional. The destination height.
487 * @param bool $src_abs Optional. If the source crop points are absolute.
488 * @return bool|WP_Error
490 public function crop( $src_x, $src_y, $src_w, $src_h, $dst_w = null, $dst_h = null, $src_abs = false ) {
497 $this->image->cropImage( $src_w, $src_h, $src_x, $src_y );
498 $this->image->setImagePage( $src_w, $src_h, 0, 0);
500 if ( $dst_w || $dst_h ) {
501 // If destination width/height isn't specified, use same as
502 // width/height from source.
508 $thumb_result = $this->thumbnail_image( $dst_w, $dst_h );
509 if ( is_wp_error( $thumb_result ) ) {
510 return $thumb_result;
513 return $this->update_size();
516 catch ( Exception $e ) {
517 return new WP_Error( 'image_crop_error', $e->getMessage() );
519 return $this->update_size();
523 * Rotates current image counter-clockwise by $angle.
528 * @param float $angle
529 * @return true|WP_Error
531 public function rotate( $angle ) {
533 * $angle is 360-$angle because Imagick rotates clockwise
534 * (GD rotates counter-clockwise)
537 $this->image->rotateImage( new ImagickPixel('none'), 360-$angle );
539 // Since this changes the dimensions of the image, update the size.
540 $result = $this->update_size();
541 if ( is_wp_error( $result ) )
544 $this->image->setImagePage( $this->size['width'], $this->size['height'], 0, 0 );
546 catch ( Exception $e ) {
547 return new WP_Error( 'image_rotate_error', $e->getMessage() );
553 * Flips current image.
558 * @param bool $horz Flip along Horizontal Axis
559 * @param bool $vert Flip along Vertical Axis
560 * @return true|WP_Error
562 public function flip( $horz, $vert ) {
565 $this->image->flipImage();
568 $this->image->flopImage();
570 catch ( Exception $e ) {
571 return new WP_Error( 'image_flip_error', $e->getMessage() );
577 * Saves current image to file.
582 * @param string $destfilename
583 * @param string $mime_type
584 * @return array|WP_Error {'path'=>string, 'file'=>string, 'width'=>int, 'height'=>int, 'mime-type'=>string}
586 public function save( $destfilename = null, $mime_type = null ) {
587 $saved = $this->_save( $this->image, $destfilename, $mime_type );
589 if ( ! is_wp_error( $saved ) ) {
590 $this->file = $saved['path'];
591 $this->mime_type = $saved['mime-type'];
594 $this->image->setImageFormat( strtoupper( $this->get_extension( $this->mime_type ) ) );
596 catch ( Exception $e ) {
597 return new WP_Error( 'image_save_error', $e->getMessage(), $this->file );
606 * @param Imagick $image
607 * @param string $filename
608 * @param string $mime_type
609 * @return array|WP_Error
611 protected function _save( $image, $filename = null, $mime_type = null ) {
612 list( $filename, $extension, $mime_type ) = $this->get_output_format( $filename, $mime_type );
615 $filename = $this->generate_filename( null, null, $extension );
618 // Store initial Format
619 $orig_format = $this->image->getImageFormat();
621 $this->image->setImageFormat( strtoupper( $this->get_extension( $mime_type ) ) );
622 $this->make_image( $filename, array( $image, 'writeImage' ), array( $filename ) );
624 // Reset original Format
625 $this->image->setImageFormat( $orig_format );
627 catch ( Exception $e ) {
628 return new WP_Error( 'image_save_error', $e->getMessage(), $filename );
631 // Set correct file permissions
632 $stat = stat( dirname( $filename ) );
633 $perms = $stat['mode'] & 0000666; //same permissions as parent folder, strip off the executable bits
634 @ chmod( $filename, $perms );
636 /** This filter is documented in wp-includes/class-wp-image-editor-gd.php */
639 'file' => wp_basename( apply_filters( 'image_make_intermediate_size', $filename ) ),
640 'width' => $this->size['width'],
641 'height' => $this->size['height'],
642 'mime-type' => $mime_type,
647 * Streams current image to browser.
652 * @param string $mime_type
653 * @return true|WP_Error
655 public function stream( $mime_type = null ) {
656 list( $filename, $extension, $mime_type ) = $this->get_output_format( null, $mime_type );
659 // Temporarily change format for stream
660 $this->image->setImageFormat( strtoupper( $extension ) );
662 // Output stream of image content
663 header( "Content-Type: $mime_type" );
664 print $this->image->getImageBlob();
666 // Reset Image to original Format
667 $this->image->setImageFormat( $this->get_extension( $this->mime_type ) );
669 catch ( Exception $e ) {
670 return new WP_Error( 'image_stream_error', $e->getMessage() );
677 * Strips all image meta except color profiles from an image.
682 * @return true|WP_Error True if stripping metadata was successful. WP_Error object on error.
684 protected function strip_meta() {
686 if ( ! is_callable( array( $this->image, 'getImageProfiles' ) ) ) {
687 /* translators: %s: ImageMagick method name */
688 return new WP_Error( 'image_strip_meta_error', sprintf( __( '%s is required to strip image meta.' ), '<code>Imagick::getImageProfiles()</code>' ) );
691 if ( ! is_callable( array( $this->image, 'removeImageProfile' ) ) ) {
692 /* translators: %s: ImageMagick method name */
693 return new WP_Error( 'image_strip_meta_error', sprintf( __( '%s is required to strip image meta.' ), '<code>Imagick::removeImageProfile()</code>' ) );
697 * Protect a few profiles from being stripped for the following reasons:
699 * - icc: Color profile information
700 * - icm: Color profile information
701 * - iptc: Copyright data
702 * - exif: Orientation data
703 * - xmp: Rights usage data
705 $protected_profiles = array(
715 foreach ( $this->image->getImageProfiles( '*', true ) as $key => $value ) {
716 if ( ! in_array( $key, $protected_profiles ) ) {
717 $this->image->removeImageProfile( $key );
721 } catch ( Exception $e ) {
722 return new WP_Error( 'image_strip_meta_error', $e->getMessage() );