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