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 );
141 * Even though Imagick uses less PHP memory than GD, set higher limit
142 * for users that have low PHP.ini limits.
144 wp_raise_memory_limit( 'image' );
147 $this->image = new Imagick( $this->file );
149 if ( ! $this->image->valid() )
150 return new WP_Error( 'invalid_image', __('File is not an image.'), $this->file);
152 // Select the first frame to handle animated images properly
153 if ( is_callable( array( $this->image, 'setIteratorIndex' ) ) )
154 $this->image->setIteratorIndex(0);
156 $this->mime_type = $this->get_mime_type( $this->image->getImageFormat() );
158 catch ( Exception $e ) {
159 return new WP_Error( 'invalid_image', $e->getMessage(), $this->file );
162 $updated_size = $this->update_size();
163 if ( is_wp_error( $updated_size ) ) {
164 return $updated_size;
167 return $this->set_quality();
171 * Sets Image Compression quality on a 1-100% scale.
176 * @param int $quality Compression Quality. Range: [1,100]
177 * @return true|WP_Error True if set successfully; WP_Error on failure.
179 public function set_quality( $quality = null ) {
180 $quality_result = parent::set_quality( $quality );
181 if ( is_wp_error( $quality_result ) ) {
182 return $quality_result;
184 $quality = $this->get_quality();
188 if ( 'image/jpeg' == $this->mime_type ) {
189 $this->image->setImageCompressionQuality( $quality );
190 $this->image->setImageCompression( imagick::COMPRESSION_JPEG );
193 $this->image->setImageCompressionQuality( $quality );
196 catch ( Exception $e ) {
197 return new WP_Error( 'image_quality_error', $e->getMessage() );
204 * Sets or updates current image size.
212 * @return true|WP_Error
214 protected function update_size( $width = null, $height = null ) {
216 if ( !$width || !$height ) {
218 $size = $this->image->getImageGeometry();
220 catch ( Exception $e ) {
221 return new WP_Error( 'invalid_image', __( 'Could not read image size.' ), $this->file );
226 $width = $size['width'];
229 $height = $size['height'];
231 return parent::update_size( $width, $height );
235 * Resizes current image.
237 * At minimum, either a height or width must be provided.
238 * If one of the two is set to null, the resize will
239 * maintain aspect ratio according to the provided dimension.
244 * @param int|null $max_w Image width.
245 * @param int|null $max_h Image height.
247 * @return bool|WP_Error
249 public function resize( $max_w, $max_h, $crop = false ) {
250 if ( ( $this->size['width'] == $max_w ) && ( $this->size['height'] == $max_h ) )
253 $dims = image_resize_dimensions( $this->size['width'], $this->size['height'], $max_w, $max_h, $crop );
255 return new WP_Error( 'error_getting_dimensions', __('Could not calculate resized image dimensions') );
256 list( $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h ) = $dims;
259 return $this->crop( $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h );
262 // Execute the resize
263 $thumb_result = $this->thumbnail_image( $dst_w, $dst_h );
264 if ( is_wp_error( $thumb_result ) ) {
265 return $thumb_result;
268 return $this->update_size( $dst_w, $dst_h );
272 * Efficiently resize the current image
274 * This is a WordPress specific implementation of Imagick::thumbnailImage(),
275 * which resizes an image to given dimensions and removes any associated profiles.
280 * @param int $dst_w The destination width.
281 * @param int $dst_h The destination height.
282 * @param string $filter_name Optional. The Imagick filter to use when resizing. Default 'FILTER_TRIANGLE'.
283 * @param bool $strip_meta Optional. Strip all profiles, excluding color profiles, from the image. Default true.
284 * @return bool|WP_Error
286 protected function thumbnail_image( $dst_w, $dst_h, $filter_name = 'FILTER_TRIANGLE', $strip_meta = true ) {
287 $allowed_filters = array(
306 * Set the filter value if '$filter_name' name is in our whitelist and the related
307 * Imagick constant is defined or fall back to our default filter.
309 if ( in_array( $filter_name, $allowed_filters ) && defined( 'Imagick::' . $filter_name ) ) {
310 $filter = constant( 'Imagick::' . $filter_name );
312 $filter = defined( 'Imagick::FILTER_TRIANGLE' ) ? Imagick::FILTER_TRIANGLE : false;
316 * Filters whether to strip metadata from images when they're resized.
318 * This filter only applies when resizing using the Imagick editor since GD
319 * always strips profiles by default.
323 * @param bool $strip_meta Whether to strip image metadata during resizing. Default true.
325 if ( apply_filters( 'image_strip_meta', $strip_meta ) ) {
326 $this->strip_meta(); // Fail silently if not supported.
331 * To be more efficient, resample large images to 5x the destination size before resizing
332 * whenever the output size is less that 1/3 of the original image size (1/3^2 ~= .111),
333 * unless we would be resampling to a scale smaller than 128x128.
335 if ( is_callable( array( $this->image, 'sampleImage' ) ) ) {
336 $resize_ratio = ( $dst_w / $this->size['width'] ) * ( $dst_h / $this->size['height'] );
339 if ( $resize_ratio < .111 && ( $dst_w * $sample_factor > 128 && $dst_h * $sample_factor > 128 ) ) {
340 $this->image->sampleImage( $dst_w * $sample_factor, $dst_h * $sample_factor );
345 * Use resizeImage() when it's available and a valid filter value is set.
346 * Otherwise, fall back to the scaleImage() method for resizing, which
347 * results in better image quality over resizeImage() with default filter
348 * settings and retains backward compatibility with pre 4.5 functionality.
350 if ( is_callable( array( $this->image, 'resizeImage' ) ) && $filter ) {
351 $this->image->setOption( 'filter:support', '2.0' );
352 $this->image->resizeImage( $dst_w, $dst_h, $filter, 1 );
354 $this->image->scaleImage( $dst_w, $dst_h );
357 // Set appropriate quality settings after resizing.
358 if ( 'image/jpeg' == $this->mime_type ) {
359 if ( is_callable( array( $this->image, 'unsharpMaskImage' ) ) ) {
360 $this->image->unsharpMaskImage( 0.25, 0.25, 8, 0.065 );
363 $this->image->setOption( 'jpeg:fancy-upsampling', 'off' );
366 if ( 'image/png' === $this->mime_type ) {
367 $this->image->setOption( 'png:compression-filter', '5' );
368 $this->image->setOption( 'png:compression-level', '9' );
369 $this->image->setOption( 'png:compression-strategy', '1' );
370 $this->image->setOption( 'png:exclude-chunk', 'all' );
374 * If alpha channel is not defined, set it opaque.
376 * Note that Imagick::getImageAlphaChannel() is only available if Imagick
377 * has been compiled against ImageMagick version 6.4.0 or newer.
379 if ( is_callable( array( $this->image, 'getImageAlphaChannel' ) )
380 && is_callable( array( $this->image, 'setImageAlphaChannel' ) )
381 && defined( 'Imagick::ALPHACHANNEL_UNDEFINED' )
382 && defined( 'Imagick::ALPHACHANNEL_OPAQUE' )
384 if ( $this->image->getImageAlphaChannel() === Imagick::ALPHACHANNEL_UNDEFINED ) {
385 $this->image->setImageAlphaChannel( Imagick::ALPHACHANNEL_OPAQUE );
389 // Limit the bit depth of resized images to 8 bits per channel.
390 if ( is_callable( array( $this->image, 'getImageDepth' ) ) && is_callable( array( $this->image, 'setImageDepth' ) ) ) {
391 if ( 8 < $this->image->getImageDepth() ) {
392 $this->image->setImageDepth( 8 );
396 if ( is_callable( array( $this->image, 'setInterlaceScheme' ) ) && defined( 'Imagick::INTERLACE_NO' ) ) {
397 $this->image->setInterlaceScheme( Imagick::INTERLACE_NO );
401 catch ( Exception $e ) {
402 return new WP_Error( 'image_resize_error', $e->getMessage() );
407 * Resize multiple images from a single source.
412 * @param array $sizes {
413 * An array of image size arrays. Default sizes are 'small', 'medium', 'medium_large', 'large'.
415 * Either a height or width must be provided.
416 * If one of the two is set to null, the resize will
417 * maintain aspect ratio according to the provided dimension.
419 * @type array $size {
420 * Array of height, width values, and whether to crop.
422 * @type int $width Image width. Optional if `$height` is specified.
423 * @type int $height Image height. Optional if `$width` is specified.
424 * @type bool $crop Optional. Whether to crop the image. Default false.
427 * @return array An array of resized images' metadata by size.
429 public function multi_resize( $sizes ) {
431 $orig_size = $this->size;
432 $orig_image = $this->image->getImage();
434 foreach ( $sizes as $size => $size_data ) {
435 if ( ! $this->image )
436 $this->image = $orig_image->getImage();
438 if ( ! isset( $size_data['width'] ) && ! isset( $size_data['height'] ) ) {
442 if ( ! isset( $size_data['width'] ) ) {
443 $size_data['width'] = null;
445 if ( ! isset( $size_data['height'] ) ) {
446 $size_data['height'] = null;
449 if ( ! isset( $size_data['crop'] ) ) {
450 $size_data['crop'] = false;
453 $resize_result = $this->resize( $size_data['width'], $size_data['height'], $size_data['crop'] );
454 $duplicate = ( ( $orig_size['width'] == $size_data['width'] ) && ( $orig_size['height'] == $size_data['height'] ) );
456 if ( ! is_wp_error( $resize_result ) && ! $duplicate ) {
457 $resized = $this->_save( $this->image );
459 $this->image->clear();
460 $this->image->destroy();
463 if ( ! is_wp_error( $resized ) && $resized ) {
464 unset( $resized['path'] );
465 $metadata[$size] = $resized;
469 $this->size = $orig_size;
472 $this->image = $orig_image;
483 * @param int $src_x The start x position to crop from.
484 * @param int $src_y The start y position to crop from.
485 * @param int $src_w The width to crop.
486 * @param int $src_h The height to crop.
487 * @param int $dst_w Optional. The destination width.
488 * @param int $dst_h Optional. The destination height.
489 * @param bool $src_abs Optional. If the source crop points are absolute.
490 * @return bool|WP_Error
492 public function crop( $src_x, $src_y, $src_w, $src_h, $dst_w = null, $dst_h = null, $src_abs = false ) {
499 $this->image->cropImage( $src_w, $src_h, $src_x, $src_y );
500 $this->image->setImagePage( $src_w, $src_h, 0, 0);
502 if ( $dst_w || $dst_h ) {
503 // If destination width/height isn't specified, use same as
504 // width/height from source.
510 $thumb_result = $this->thumbnail_image( $dst_w, $dst_h );
511 if ( is_wp_error( $thumb_result ) ) {
512 return $thumb_result;
515 return $this->update_size();
518 catch ( Exception $e ) {
519 return new WP_Error( 'image_crop_error', $e->getMessage() );
521 return $this->update_size();
525 * Rotates current image counter-clockwise by $angle.
530 * @param float $angle
531 * @return true|WP_Error
533 public function rotate( $angle ) {
535 * $angle is 360-$angle because Imagick rotates clockwise
536 * (GD rotates counter-clockwise)
539 $this->image->rotateImage( new ImagickPixel('none'), 360-$angle );
541 // Since this changes the dimensions of the image, update the size.
542 $result = $this->update_size();
543 if ( is_wp_error( $result ) )
546 $this->image->setImagePage( $this->size['width'], $this->size['height'], 0, 0 );
548 catch ( Exception $e ) {
549 return new WP_Error( 'image_rotate_error', $e->getMessage() );
555 * Flips current image.
560 * @param bool $horz Flip along Horizontal Axis
561 * @param bool $vert Flip along Vertical Axis
562 * @return true|WP_Error
564 public function flip( $horz, $vert ) {
567 $this->image->flipImage();
570 $this->image->flopImage();
572 catch ( Exception $e ) {
573 return new WP_Error( 'image_flip_error', $e->getMessage() );
579 * Saves current image to file.
584 * @param string $destfilename
585 * @param string $mime_type
586 * @return array|WP_Error {'path'=>string, 'file'=>string, 'width'=>int, 'height'=>int, 'mime-type'=>string}
588 public function save( $destfilename = null, $mime_type = null ) {
589 $saved = $this->_save( $this->image, $destfilename, $mime_type );
591 if ( ! is_wp_error( $saved ) ) {
592 $this->file = $saved['path'];
593 $this->mime_type = $saved['mime-type'];
596 $this->image->setImageFormat( strtoupper( $this->get_extension( $this->mime_type ) ) );
598 catch ( Exception $e ) {
599 return new WP_Error( 'image_save_error', $e->getMessage(), $this->file );
608 * @param Imagick $image
609 * @param string $filename
610 * @param string $mime_type
611 * @return array|WP_Error
613 protected function _save( $image, $filename = null, $mime_type = null ) {
614 list( $filename, $extension, $mime_type ) = $this->get_output_format( $filename, $mime_type );
617 $filename = $this->generate_filename( null, null, $extension );
620 // Store initial Format
621 $orig_format = $this->image->getImageFormat();
623 $this->image->setImageFormat( strtoupper( $this->get_extension( $mime_type ) ) );
624 $this->make_image( $filename, array( $image, 'writeImage' ), array( $filename ) );
626 // Reset original Format
627 $this->image->setImageFormat( $orig_format );
629 catch ( Exception $e ) {
630 return new WP_Error( 'image_save_error', $e->getMessage(), $filename );
633 // Set correct file permissions
634 $stat = stat( dirname( $filename ) );
635 $perms = $stat['mode'] & 0000666; //same permissions as parent folder, strip off the executable bits
636 @ chmod( $filename, $perms );
638 /** This filter is documented in wp-includes/class-wp-image-editor-gd.php */
641 'file' => wp_basename( apply_filters( 'image_make_intermediate_size', $filename ) ),
642 'width' => $this->size['width'],
643 'height' => $this->size['height'],
644 'mime-type' => $mime_type,
649 * Streams current image to browser.
654 * @param string $mime_type
655 * @return true|WP_Error
657 public function stream( $mime_type = null ) {
658 list( $filename, $extension, $mime_type ) = $this->get_output_format( null, $mime_type );
661 // Temporarily change format for stream
662 $this->image->setImageFormat( strtoupper( $extension ) );
664 // Output stream of image content
665 header( "Content-Type: $mime_type" );
666 print $this->image->getImageBlob();
668 // Reset Image to original Format
669 $this->image->setImageFormat( $this->get_extension( $this->mime_type ) );
671 catch ( Exception $e ) {
672 return new WP_Error( 'image_stream_error', $e->getMessage() );
679 * Strips all image meta except color profiles from an image.
684 * @return true|WP_Error True if stripping metadata was successful. WP_Error object on error.
686 protected function strip_meta() {
688 if ( ! is_callable( array( $this->image, 'getImageProfiles' ) ) ) {
689 /* translators: %s: ImageMagick method name */
690 return new WP_Error( 'image_strip_meta_error', sprintf( __( '%s is required to strip image meta.' ), '<code>Imagick::getImageProfiles()</code>' ) );
693 if ( ! is_callable( array( $this->image, 'removeImageProfile' ) ) ) {
694 /* translators: %s: ImageMagick method name */
695 return new WP_Error( 'image_strip_meta_error', sprintf( __( '%s is required to strip image meta.' ), '<code>Imagick::removeImageProfile()</code>' ) );
699 * Protect a few profiles from being stripped for the following reasons:
701 * - icc: Color profile information
702 * - icm: Color profile information
703 * - iptc: Copyright data
704 * - exif: Orientation data
705 * - xmp: Rights usage data
707 $protected_profiles = array(
717 foreach ( $this->image->getImageProfiles( '*', true ) as $key => $value ) {
718 if ( ! in_array( $key, $protected_profiles ) ) {
719 $this->image->removeImageProfile( $key );
723 } catch ( Exception $e ) {
724 return new WP_Error( 'image_strip_meta_error', $e->getMessage() );