]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/class-wp-image-editor-imagick.php
WordPress 4.3-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' ) || ! class_exists( 'ImagickPixel' ) )
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', '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          *         @type int  ['width']  Optional. Image width.
281          *         @type int  ['height'] Optional. Image height.
282          *         @type bool $crop   Optional. Whether to crop the image. Default false.
283          *     }
284          * }
285          * @return array An array of resized images' metadata by size.
286          */
287         public function multi_resize( $sizes ) {
288                 $metadata = array();
289                 $orig_size = $this->size;
290                 $orig_image = $this->image->getImage();
291
292                 foreach ( $sizes as $size => $size_data ) {
293                         if ( ! $this->image )
294                                 $this->image = $orig_image->getImage();
295
296                         if ( ! isset( $size_data['width'] ) && ! isset( $size_data['height'] ) ) {
297                                 continue;
298                         }
299
300                         if ( ! isset( $size_data['width'] ) ) {
301                                 $size_data['width'] = null;
302                         }
303                         if ( ! isset( $size_data['height'] ) ) {
304                                 $size_data['height'] = null;
305                         }
306
307                         if ( ! isset( $size_data['crop'] ) ) {
308                                 $size_data['crop'] = false;
309                         }
310
311                         $resize_result = $this->resize( $size_data['width'], $size_data['height'], $size_data['crop'] );
312                         $duplicate = ( ( $orig_size['width'] == $size_data['width'] ) && ( $orig_size['height'] == $size_data['height'] ) );
313
314                         if ( ! is_wp_error( $resize_result ) && ! $duplicate ) {
315                                 $resized = $this->_save( $this->image );
316
317                                 $this->image->clear();
318                                 $this->image->destroy();
319                                 $this->image = null;
320
321                                 if ( ! is_wp_error( $resized ) && $resized ) {
322                                         unset( $resized['path'] );
323                                         $metadata[$size] = $resized;
324                                 }
325                         }
326
327                         $this->size = $orig_size;
328                 }
329
330                 $this->image = $orig_image;
331
332                 return $metadata;
333         }
334
335         /**
336          * Crops Image.
337          *
338          * @since 3.5.0
339          * @access public
340          *
341          * @param int  $src_x The start x position to crop from.
342          * @param int  $src_y The start y position to crop from.
343          * @param int  $src_w The width to crop.
344          * @param int  $src_h The height to crop.
345          * @param int  $dst_w Optional. The destination width.
346          * @param int  $dst_h Optional. The destination height.
347          * @param bool $src_abs Optional. If the source crop points are absolute.
348          * @return bool|WP_Error
349          */
350         public function crop( $src_x, $src_y, $src_w, $src_h, $dst_w = null, $dst_h = null, $src_abs = false ) {
351                 if ( $src_abs ) {
352                         $src_w -= $src_x;
353                         $src_h -= $src_y;
354                 }
355
356                 try {
357                         $this->image->cropImage( $src_w, $src_h, $src_x, $src_y );
358                         $this->image->setImagePage( $src_w, $src_h, 0, 0);
359
360                         if ( $dst_w || $dst_h ) {
361                                 // If destination width/height isn't specified, use same as
362                                 // width/height from source.
363                                 if ( ! $dst_w )
364                                         $dst_w = $src_w;
365                                 if ( ! $dst_h )
366                                         $dst_h = $src_h;
367
368                                 $this->image->scaleImage( $dst_w, $dst_h );
369                                 return $this->update_size();
370                         }
371                 }
372                 catch ( Exception $e ) {
373                         return new WP_Error( 'image_crop_error', $e->getMessage() );
374                 }
375                 return $this->update_size();
376         }
377
378         /**
379          * Rotates current image counter-clockwise by $angle.
380          *
381          * @since 3.5.0
382          * @access public
383          *
384          * @param float $angle
385          * @return true|WP_Error
386          */
387         public function rotate( $angle ) {
388                 /**
389                  * $angle is 360-$angle because Imagick rotates clockwise
390                  * (GD rotates counter-clockwise)
391                  */
392                 try {
393                         $this->image->rotateImage( new ImagickPixel('none'), 360-$angle );
394
395                         // Since this changes the dimensions of the image, update the size.
396                         $result = $this->update_size();
397                         if ( is_wp_error( $result ) )
398                                 return $result;
399
400                         $this->image->setImagePage( $this->size['width'], $this->size['height'], 0, 0 );
401                 }
402                 catch ( Exception $e ) {
403                         return new WP_Error( 'image_rotate_error', $e->getMessage() );
404                 }
405                 return true;
406         }
407
408         /**
409          * Flips current image.
410          *
411          * @since 3.5.0
412          * @access public
413          *
414          * @param bool $horz Flip along Horizontal Axis
415          * @param bool $vert Flip along Vertical Axis
416          * @return true|WP_Error
417          */
418         public function flip( $horz, $vert ) {
419                 try {
420                         if ( $horz )
421                                 $this->image->flipImage();
422
423                         if ( $vert )
424                                 $this->image->flopImage();
425                 }
426                 catch ( Exception $e ) {
427                         return new WP_Error( 'image_flip_error', $e->getMessage() );
428                 }
429                 return true;
430         }
431
432         /**
433          * Saves current image to file.
434          *
435          * @since 3.5.0
436          * @access public
437          *
438          * @param string $destfilename
439          * @param string $mime_type
440          * @return array|WP_Error {'path'=>string, 'file'=>string, 'width'=>int, 'height'=>int, 'mime-type'=>string}
441          */
442         public function save( $destfilename = null, $mime_type = null ) {
443                 $saved = $this->_save( $this->image, $destfilename, $mime_type );
444
445                 if ( ! is_wp_error( $saved ) ) {
446                         $this->file = $saved['path'];
447                         $this->mime_type = $saved['mime-type'];
448
449                         try {
450                                 $this->image->setImageFormat( strtoupper( $this->get_extension( $this->mime_type ) ) );
451                         }
452                         catch ( Exception $e ) {
453                                 return new WP_Error( 'image_save_error', $e->getMessage(), $this->file );
454                         }
455                 }
456
457                 return $saved;
458         }
459
460         /**
461          *
462          * @param Imagick $image
463          * @param string $filename
464          * @param string $mime_type
465          * @return array|WP_Error
466          */
467         protected function _save( $image, $filename = null, $mime_type = null ) {
468                 list( $filename, $extension, $mime_type ) = $this->get_output_format( $filename, $mime_type );
469
470                 if ( ! $filename )
471                         $filename = $this->generate_filename( null, null, $extension );
472
473                 try {
474                         // Store initial Format
475                         $orig_format = $this->image->getImageFormat();
476
477                         $this->image->setImageFormat( strtoupper( $this->get_extension( $mime_type ) ) );
478                         $this->make_image( $filename, array( $image, 'writeImage' ), array( $filename ) );
479
480                         // Reset original Format
481                         $this->image->setImageFormat( $orig_format );
482                 }
483                 catch ( Exception $e ) {
484                         return new WP_Error( 'image_save_error', $e->getMessage(), $filename );
485                 }
486
487                 // Set correct file permissions
488                 $stat = stat( dirname( $filename ) );
489                 $perms = $stat['mode'] & 0000666; //same permissions as parent folder, strip off the executable bits
490                 @ chmod( $filename, $perms );
491
492                 /** This filter is documented in wp-includes/class-wp-image-editor-gd.php */
493                 return array(
494                         'path'      => $filename,
495                         'file'      => wp_basename( apply_filters( 'image_make_intermediate_size', $filename ) ),
496                         'width'     => $this->size['width'],
497                         'height'    => $this->size['height'],
498                         'mime-type' => $mime_type,
499                 );
500         }
501
502         /**
503          * Streams current image to browser.
504          *
505          * @since 3.5.0
506          * @access public
507          *
508          * @param string $mime_type
509          * @return true|WP_Error
510          */
511         public function stream( $mime_type = null ) {
512                 list( $filename, $extension, $mime_type ) = $this->get_output_format( null, $mime_type );
513
514                 try {
515                         // Temporarily change format for stream
516                         $this->image->setImageFormat( strtoupper( $extension ) );
517
518                         // Output stream of image content
519                         header( "Content-Type: $mime_type" );
520                         print $this->image->getImageBlob();
521
522                         // Reset Image to original Format
523                         $this->image->setImageFormat( $this->get_extension( $this->mime_type ) );
524                 }
525                 catch ( Exception $e ) {
526                         return new WP_Error( 'image_stream_error', $e->getMessage() );
527                 }
528
529                 return true;
530         }
531 }