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