]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/class-wp-image-editor-imagick.php
WordPress 4.4.2-scripts
[autoinstalls/wordpress.git] / wp-includes / class-wp-image-editor-imagick.php
1 <?php
2 /**
3  * WordPress Imagick Image Editor
4  *
5  * @package WordPress
6  * @subpackage Image_Editor
7  */
8
9 /**
10  * WordPress Image Editor Class for Image Manipulation through Imagick PHP Module
11  *
12  * @since 3.5.0
13  * @package WordPress
14  * @subpackage Image_Editor
15  * @uses WP_Image_Editor Extends class
16  */
17 class WP_Image_Editor_Imagick extends WP_Image_Editor {
18         /**
19          * Imagick object.
20          *
21          * @access protected
22          * @var Imagick
23          */
24         protected $image;
25
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();
31                 }
32         }
33
34         /**
35          * Checks to see if current environment supports Imagick.
36          *
37          * We require Imagick 2.2.0 or greater, based on whether the queryFormats()
38          * method can be called statically.
39          *
40          * @since 3.5.0
41          *
42          * @static
43          * @access public
44          *
45          * @param array $args
46          * @return bool
47          */
48         public static function test( $args = array() ) {
49
50                 // First, test Imagick's extension and classes.
51                 if ( ! extension_loaded( 'imagick' ) || ! class_exists( 'Imagick', false ) || ! class_exists( 'ImagickPixel', false ) )
52                         return false;
53
54                 if ( version_compare( phpversion( 'imagick' ), '2.2.0', '<' ) )
55                         return false;
56
57                 $required_methods = array(
58                         'clear',
59                         'destroy',
60                         'valid',
61                         'getimage',
62                         'writeimage',
63                         'getimageblob',
64                         'getimagegeometry',
65                         'getimageformat',
66                         'setimageformat',
67                         'setimagecompression',
68                         'setimagecompressionquality',
69                         'setimagepage',
70                         'scaleimage',
71                         'cropimage',
72                         'rotateimage',
73                         'flipimage',
74                         'flopimage',
75                 );
76
77                 // Now, test for deep requirements within Imagick.
78                 if ( ! defined( 'imagick::COMPRESSION_JPEG' ) )
79                         return false;
80
81                 if ( array_diff( $required_methods, get_class_methods( 'Imagick' ) ) )
82                         return false;
83
84                 return true;
85         }
86
87         /**
88          * Checks to see if editor supports the mime-type specified.
89          *
90          * @since 3.5.0
91          *
92          * @static
93          * @access public
94          *
95          * @param string $mime_type
96          * @return bool
97          */
98         public static function supports_mime_type( $mime_type ) {
99                 $imagick_extension = strtoupper( self::get_extension( $mime_type ) );
100
101                 if ( ! $imagick_extension )
102                         return false;
103
104                 // setIteratorIndex is optional unless mime is an animated format.
105                 // Here, we just say no if you are missing it and aren't loading a jpeg.
106                 if ( ! method_exists( 'Imagick', 'setIteratorIndex' ) && $mime_type != 'image/jpeg' )
107                                 return false;
108
109                 try {
110                         return ( (bool) @Imagick::queryFormats( $imagick_extension ) );
111                 }
112                 catch ( Exception $e ) {
113                         return false;
114                 }
115         }
116
117         /**
118          * Loads image from $this->file into new Imagick Object.
119          *
120          * @since 3.5.0
121          * @access protected
122          *
123          * @return true|WP_Error True if loaded; WP_Error on failure.
124          */
125         public function load() {
126                 if ( $this->image instanceof Imagick )
127                         return true;
128
129                 if ( ! is_file( $this->file ) && ! preg_match( '|^https?://|', $this->file ) )
130                         return new WP_Error( 'error_loading_image', __('File doesn&#8217;t exist?'), $this->file );
131
132                 /** This filter is documented in wp-includes/class-wp-image-editor-imagick.php */
133                 // Even though Imagick uses less PHP memory than GD, set higher limit for users that have low PHP.ini limits
134                 @ini_set( 'memory_limit', apply_filters( 'image_memory_limit', WP_MAX_MEMORY_LIMIT ) );
135
136                 try {
137                         $this->image = new Imagick( $this->file );
138
139                         if ( ! $this->image->valid() )
140                                 return new WP_Error( 'invalid_image', __('File is not an image.'), $this->file);
141
142                         // Select the first frame to handle animated images properly
143                         if ( is_callable( array( $this->image, 'setIteratorIndex' ) ) )
144                                 $this->image->setIteratorIndex(0);
145
146                         $this->mime_type = $this->get_mime_type( $this->image->getImageFormat() );
147                 }
148                 catch ( Exception $e ) {
149                         return new WP_Error( 'invalid_image', $e->getMessage(), $this->file );
150                 }
151
152                 $updated_size = $this->update_size();
153                 if ( is_wp_error( $updated_size ) ) {
154                         return $updated_size;
155                 }
156
157                 return $this->set_quality();
158         }
159
160         /**
161          * Sets Image Compression quality on a 1-100% scale.
162          *
163          * @since 3.5.0
164          * @access public
165          *
166          * @param int $quality Compression Quality. Range: [1,100]
167          * @return true|WP_Error True if set successfully; WP_Error on failure.
168          */
169         public function set_quality( $quality = null ) {
170                 $quality_result = parent::set_quality( $quality );
171                 if ( is_wp_error( $quality_result ) ) {
172                         return $quality_result;
173                 } else {
174                         $quality = $this->get_quality();
175                 }
176
177                 try {
178                         if ( 'image/jpeg' == $this->mime_type ) {
179                                 $this->image->setImageCompressionQuality( $quality );
180                                 $this->image->setImageCompression( imagick::COMPRESSION_JPEG );
181                         }
182                         else {
183                                 $this->image->setImageCompressionQuality( $quality );
184                         }
185                 }
186                 catch ( Exception $e ) {
187                         return new WP_Error( 'image_quality_error', $e->getMessage() );
188                 }
189
190                 return true;
191         }
192
193         /**
194          * Sets or updates current image size.
195          *
196          * @since 3.5.0
197          * @access protected
198          *
199          * @param int $width
200          * @param int $height
201          *
202          * @return true|WP_Error
203          */
204         protected function update_size( $width = null, $height = null ) {
205                 $size = null;
206                 if ( !$width || !$height ) {
207                         try {
208                                 $size = $this->image->getImageGeometry();
209                         }
210                         catch ( Exception $e ) {
211                                 return new WP_Error( 'invalid_image', __( 'Could not read image size.' ), $this->file );
212                         }
213                 }
214
215                 if ( ! $width )
216                         $width = $size['width'];
217
218                 if ( ! $height )
219                         $height = $size['height'];
220
221                 return parent::update_size( $width, $height );
222         }
223
224         /**
225          * Resizes current image.
226          *
227          * At minimum, either a height or width must be provided.
228          * If one of the two is set to null, the resize will
229          * maintain aspect ratio according to the provided dimension.
230          *
231          * @since 3.5.0
232          * @access public
233          *
234          * @param  int|null $max_w Image width.
235          * @param  int|null $max_h Image height.
236          * @param  bool     $crop
237          * @return bool|WP_Error
238          */
239         public function resize( $max_w, $max_h, $crop = false ) {
240                 if ( ( $this->size['width'] == $max_w ) && ( $this->size['height'] == $max_h ) )
241                         return true;
242
243                 $dims = image_resize_dimensions( $this->size['width'], $this->size['height'], $max_w, $max_h, $crop );
244                 if ( ! $dims )
245                         return new WP_Error( 'error_getting_dimensions', __('Could not calculate resized image dimensions') );
246                 list( $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h ) = $dims;
247
248                 if ( $crop ) {
249                         return $this->crop( $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h );
250                 }
251
252                 try {
253                         /**
254                          * @TODO: Thumbnail is more efficient, given a newer version of Imagemagick.
255                          * $this->image->thumbnailImage( $dst_w, $dst_h );
256                          */
257                         $this->image->scaleImage( $dst_w, $dst_h );
258                 }
259                 catch ( Exception $e ) {
260                         return new WP_Error( 'image_resize_error', $e->getMessage() );
261                 }
262
263                 return $this->update_size( $dst_w, $dst_h );
264         }
265
266         /**
267          * Resize multiple images from a single source.
268          *
269          * @since 3.5.0
270          * @access public
271          *
272          * @param array $sizes {
273          *     An array of image size arrays. Default sizes are 'small', 'medium', 'medium_large', 'large'.
274          *
275          *     Either a height or width must be provided.
276          *     If one of the two is set to null, the resize will
277          *     maintain aspect ratio according to the provided dimension.
278          *
279          *     @type array $size {
280          *         Array of height, width values, and whether to crop.
281          *
282          *         @type int  $width  Image width. Optional if `$height` is specified.
283          *         @type int  $height Image height. Optional if `$width` is specified.
284          *         @type bool $crop   Optional. Whether to crop the image. Default false.
285          *     }
286          * }
287          * @return array An array of resized images' metadata by size.
288          */
289         public function multi_resize( $sizes ) {
290                 $metadata = array();
291                 $orig_size = $this->size;
292                 $orig_image = $this->image->getImage();
293
294                 foreach ( $sizes as $size => $size_data ) {
295                         if ( ! $this->image )
296                                 $this->image = $orig_image->getImage();
297
298                         if ( ! isset( $size_data['width'] ) && ! isset( $size_data['height'] ) ) {
299                                 continue;
300                         }
301
302                         if ( ! isset( $size_data['width'] ) ) {
303                                 $size_data['width'] = null;
304                         }
305                         if ( ! isset( $size_data['height'] ) ) {
306                                 $size_data['height'] = null;
307                         }
308
309                         if ( ! isset( $size_data['crop'] ) ) {
310                                 $size_data['crop'] = false;
311                         }
312
313                         $resize_result = $this->resize( $size_data['width'], $size_data['height'], $size_data['crop'] );
314                         $duplicate = ( ( $orig_size['width'] == $size_data['width'] ) && ( $orig_size['height'] == $size_data['height'] ) );
315
316                         if ( ! is_wp_error( $resize_result ) && ! $duplicate ) {
317                                 $resized = $this->_save( $this->image );
318
319                                 $this->image->clear();
320                                 $this->image->destroy();
321                                 $this->image = null;
322
323                                 if ( ! is_wp_error( $resized ) && $resized ) {
324                                         unset( $resized['path'] );
325                                         $metadata[$size] = $resized;
326                                 }
327                         }
328
329                         $this->size = $orig_size;
330                 }
331
332                 $this->image = $orig_image;
333
334                 return $metadata;
335         }
336
337         /**
338          * Crops Image.
339          *
340          * @since 3.5.0
341          * @access public
342          *
343          * @param int  $src_x The start x position to crop from.
344          * @param int  $src_y The start y position to crop from.
345          * @param int  $src_w The width to crop.
346          * @param int  $src_h The height to crop.
347          * @param int  $dst_w Optional. The destination width.
348          * @param int  $dst_h Optional. The destination height.
349          * @param bool $src_abs Optional. If the source crop points are absolute.
350          * @return bool|WP_Error
351          */
352         public function crop( $src_x, $src_y, $src_w, $src_h, $dst_w = null, $dst_h = null, $src_abs = false ) {
353                 if ( $src_abs ) {
354                         $src_w -= $src_x;
355                         $src_h -= $src_y;
356                 }
357
358                 try {
359                         $this->image->cropImage( $src_w, $src_h, $src_x, $src_y );
360                         $this->image->setImagePage( $src_w, $src_h, 0, 0);
361
362                         if ( $dst_w || $dst_h ) {
363                                 // If destination width/height isn't specified, use same as
364                                 // width/height from source.
365                                 if ( ! $dst_w )
366                                         $dst_w = $src_w;
367                                 if ( ! $dst_h )
368                                         $dst_h = $src_h;
369
370                                 $this->image->scaleImage( $dst_w, $dst_h );
371                                 return $this->update_size();
372                         }
373                 }
374                 catch ( Exception $e ) {
375                         return new WP_Error( 'image_crop_error', $e->getMessage() );
376                 }
377                 return $this->update_size();
378         }
379
380         /**
381          * Rotates current image counter-clockwise by $angle.
382          *
383          * @since 3.5.0
384          * @access public
385          *
386          * @param float $angle
387          * @return true|WP_Error
388          */
389         public function rotate( $angle ) {
390                 /**
391                  * $angle is 360-$angle because Imagick rotates clockwise
392                  * (GD rotates counter-clockwise)
393                  */
394                 try {
395                         $this->image->rotateImage( new ImagickPixel('none'), 360-$angle );
396
397                         // Since this changes the dimensions of the image, update the size.
398                         $result = $this->update_size();
399                         if ( is_wp_error( $result ) )
400                                 return $result;
401
402                         $this->image->setImagePage( $this->size['width'], $this->size['height'], 0, 0 );
403                 }
404                 catch ( Exception $e ) {
405                         return new WP_Error( 'image_rotate_error', $e->getMessage() );
406                 }
407                 return true;
408         }
409
410         /**
411          * Flips current image.
412          *
413          * @since 3.5.0
414          * @access public
415          *
416          * @param bool $horz Flip along Horizontal Axis
417          * @param bool $vert Flip along Vertical Axis
418          * @return true|WP_Error
419          */
420         public function flip( $horz, $vert ) {
421                 try {
422                         if ( $horz )
423                                 $this->image->flipImage();
424
425                         if ( $vert )
426                                 $this->image->flopImage();
427                 }
428                 catch ( Exception $e ) {
429                         return new WP_Error( 'image_flip_error', $e->getMessage() );
430                 }
431                 return true;
432         }
433
434         /**
435          * Saves current image to file.
436          *
437          * @since 3.5.0
438          * @access public
439          *
440          * @param string $destfilename
441          * @param string $mime_type
442          * @return array|WP_Error {'path'=>string, 'file'=>string, 'width'=>int, 'height'=>int, 'mime-type'=>string}
443          */
444         public function save( $destfilename = null, $mime_type = null ) {
445                 $saved = $this->_save( $this->image, $destfilename, $mime_type );
446
447                 if ( ! is_wp_error( $saved ) ) {
448                         $this->file = $saved['path'];
449                         $this->mime_type = $saved['mime-type'];
450
451                         try {
452                                 $this->image->setImageFormat( strtoupper( $this->get_extension( $this->mime_type ) ) );
453                         }
454                         catch ( Exception $e ) {
455                                 return new WP_Error( 'image_save_error', $e->getMessage(), $this->file );
456                         }
457                 }
458
459                 return $saved;
460         }
461
462         /**
463          *
464          * @param Imagick $image
465          * @param string $filename
466          * @param string $mime_type
467          * @return array|WP_Error
468          */
469         protected function _save( $image, $filename = null, $mime_type = null ) {
470                 list( $filename, $extension, $mime_type ) = $this->get_output_format( $filename, $mime_type );
471
472                 if ( ! $filename )
473                         $filename = $this->generate_filename( null, null, $extension );
474
475                 try {
476                         // Store initial Format
477                         $orig_format = $this->image->getImageFormat();
478
479                         $this->image->setImageFormat( strtoupper( $this->get_extension( $mime_type ) ) );
480                         $this->make_image( $filename, array( $image, 'writeImage' ), array( $filename ) );
481
482                         // Reset original Format
483                         $this->image->setImageFormat( $orig_format );
484                 }
485                 catch ( Exception $e ) {
486                         return new WP_Error( 'image_save_error', $e->getMessage(), $filename );
487                 }
488
489                 // Set correct file permissions
490                 $stat = stat( dirname( $filename ) );
491                 $perms = $stat['mode'] & 0000666; //same permissions as parent folder, strip off the executable bits
492                 @ chmod( $filename, $perms );
493
494                 /** This filter is documented in wp-includes/class-wp-image-editor-gd.php */
495                 return array(
496                         'path'      => $filename,
497                         'file'      => wp_basename( apply_filters( 'image_make_intermediate_size', $filename ) ),
498                         'width'     => $this->size['width'],
499                         'height'    => $this->size['height'],
500                         'mime-type' => $mime_type,
501                 );
502         }
503
504         /**
505          * Streams current image to browser.
506          *
507          * @since 3.5.0
508          * @access public
509          *
510          * @param string $mime_type
511          * @return true|WP_Error
512          */
513         public function stream( $mime_type = null ) {
514                 list( $filename, $extension, $mime_type ) = $this->get_output_format( null, $mime_type );
515
516                 try {
517                         // Temporarily change format for stream
518                         $this->image->setImageFormat( strtoupper( $extension ) );
519
520                         // Output stream of image content
521                         header( "Content-Type: $mime_type" );
522                         print $this->image->getImageBlob();
523
524                         // Reset Image to original Format
525                         $this->image->setImageFormat( $this->get_extension( $this->mime_type ) );
526                 }
527                 catch ( Exception $e ) {
528                         return new WP_Error( 'image_stream_error', $e->getMessage() );
529                 }
530
531                 return true;
532         }
533 }