]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/class-wp-image-editor-imagick.php
Wordpress 3.6
[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          * Processes current image and saves to disk
246          * multiple sizes from single source.
247          *
248          * 'width' and 'height' are required.
249          * 'crop' defaults to false when not provided.
250          *
251          * @since 3.5.0
252          * @access public
253          *
254          * @param array $sizes { {'width'=>int, 'height'=>int, ['crop'=>bool]}, ... }
255          * @return array
256          */
257         public function multi_resize( $sizes ) {
258                 $metadata = array();
259                 $orig_size = $this->size;
260                 $orig_image = $this->image->getImage();
261
262                 foreach ( $sizes as $size => $size_data ) {
263                         if ( ! $this->image )
264                                 $this->image = $orig_image->getImage();
265
266                         if ( ! ( isset( $size_data['width'] ) && isset( $size_data['height'] ) ) )
267                                 continue;
268
269                         if ( ! isset( $size_data['crop'] ) )
270                                 $size_data['crop'] = false;
271
272                         $resize_result = $this->resize( $size_data['width'], $size_data['height'], $size_data['crop'] );
273
274                         if( ! is_wp_error( $resize_result ) ) {
275                                 $resized = $this->_save( $this->image );
276
277                                 $this->image->clear();
278                                 $this->image->destroy();
279                                 $this->image = null;
280
281                                 if ( ! is_wp_error( $resized ) && $resized ) {
282                                         unset( $resized['path'] );
283                                         $metadata[$size] = $resized;
284                                 }
285                         }
286
287                         $this->size = $orig_size;
288                 }
289
290                 $this->image = $orig_image;
291
292                 return $metadata;
293         }
294
295         /**
296          * Crops Image.
297          *
298          * @since 3.5.0
299          * @access public
300          *
301          * @param string|int $src The source file or Attachment ID.
302          * @param int $src_x The start x position to crop from.
303          * @param int $src_y The start y position to crop from.
304          * @param int $src_w The width to crop.
305          * @param int $src_h The height to crop.
306          * @param int $dst_w Optional. The destination width.
307          * @param int $dst_h Optional. The destination height.
308          * @param boolean $src_abs Optional. If the source crop points are absolute.
309          * @return boolean|WP_Error
310          */
311         public function crop( $src_x, $src_y, $src_w, $src_h, $dst_w = null, $dst_h = null, $src_abs = false ) {
312                 if ( $src_abs ) {
313                         $src_w -= $src_x;
314                         $src_h -= $src_y;
315                 }
316
317                 try {
318                         $this->image->cropImage( $src_w, $src_h, $src_x, $src_y );
319                         $this->image->setImagePage( $src_w, $src_h, 0, 0);
320
321                         if ( $dst_w || $dst_h ) {
322                                 // If destination width/height isn't specified, use same as
323                                 // width/height from source.
324                                 if ( ! $dst_w )
325                                         $dst_w = $src_w;
326                                 if ( ! $dst_h )
327                                         $dst_h = $src_h;
328
329                                 $this->image->scaleImage( $dst_w, $dst_h );
330                                 return $this->update_size();
331                         }
332                 }
333                 catch ( Exception $e ) {
334                         return new WP_Error( 'image_crop_error', $e->getMessage() );
335                 }
336                 return $this->update_size();
337         }
338
339         /**
340          * Rotates current image counter-clockwise by $angle.
341          *
342          * @since 3.5.0
343          * @access public
344          *
345          * @param float $angle
346          * @return boolean|WP_Error
347          */
348         public function rotate( $angle ) {
349                 /**
350                  * $angle is 360-$angle because Imagick rotates clockwise
351                  * (GD rotates counter-clockwise)
352                  */
353                 try {
354                         $this->image->rotateImage( new ImagickPixel('none'), 360-$angle );
355                 }
356                 catch ( Exception $e ) {
357                         return new WP_Error( 'image_rotate_error', $e->getMessage() );
358                 }
359                 return $this->update_size();
360         }
361
362         /**
363          * Flips current image.
364          *
365          * @since 3.5.0
366          * @access public
367          *
368          * @param boolean $horz Flip along Horizontal Axis
369          * @param boolean $vert Flip along Vertical Axis
370          * @returns boolean|WP_Error
371          */
372         public function flip( $horz, $vert ) {
373                 try {
374                         if ( $horz )
375                                 $this->image->flipImage();
376
377                         if ( $vert )
378                                 $this->image->flopImage();
379                 }
380                 catch ( Exception $e ) {
381                         return new WP_Error( 'image_flip_error', $e->getMessage() );
382                 }
383                 return true;
384         }
385
386         /**
387          * Saves current image to file.
388          *
389          * @since 3.5.0
390          * @access public
391          *
392          * @param string $destfilename
393          * @param string $mime_type
394          * @return array|WP_Error {'path'=>string, 'file'=>string, 'width'=>int, 'height'=>int, 'mime-type'=>string}
395          */
396         public function save( $destfilename = null, $mime_type = null ) {
397                 $saved = $this->_save( $this->image, $destfilename, $mime_type );
398
399                 if ( ! is_wp_error( $saved ) ) {
400                         $this->file = $saved['path'];
401                         $this->mime_type = $saved['mime-type'];
402
403                         try {
404                                 $this->image->setImageFormat( strtoupper( $this->get_extension( $this->mime_type ) ) );
405                         }
406                         catch ( Exception $e ) {
407                                 return new WP_Error( 'image_save_error', $e->getMessage(), $this->file );
408                         }
409                 }
410
411                 return $saved;
412         }
413
414         protected function _save( $image, $filename = null, $mime_type = null ) {
415                 list( $filename, $extension, $mime_type ) = $this->get_output_format( $filename, $mime_type );
416
417                 if ( ! $filename )
418                         $filename = $this->generate_filename( null, null, $extension );
419
420                 try {
421                         // Store initial Format
422                         $orig_format = $this->image->getImageFormat();
423
424                         $this->image->setImageFormat( strtoupper( $this->get_extension( $mime_type ) ) );
425                         $this->make_image( $filename, array( $image, 'writeImage' ), array( $filename ) );
426
427                         // Reset original Format
428                         $this->image->setImageFormat( $orig_format );
429                 }
430                 catch ( Exception $e ) {
431                         return new WP_Error( 'image_save_error', $e->getMessage(), $filename );
432                 }
433
434                 // Set correct file permissions
435                 $stat = stat( dirname( $filename ) );
436                 $perms = $stat['mode'] & 0000666; //same permissions as parent folder, strip off the executable bits
437                 @ chmod( $filename, $perms );
438
439                 return array(
440                         'path' => $filename,
441                         'file' => wp_basename( apply_filters( 'image_make_intermediate_size', $filename ) ),
442                         'width' => $this->size['width'],
443                         'height' => $this->size['height'],
444                         'mime-type' => $mime_type,
445                 );
446         }
447
448         /**
449          * Streams current image to browser.
450          *
451          * @since 3.5.0
452          * @access public
453          *
454          * @param string $mime_type
455          * @return boolean|WP_Error
456          */
457         public function stream( $mime_type = null ) {
458                 list( $filename, $extension, $mime_type ) = $this->get_output_format( null, $mime_type );
459
460                 try {
461                         // Temporarily change format for stream
462                         $this->image->setImageFormat( strtoupper( $extension ) );
463
464                         // Output stream of image content
465                         header( "Content-Type: $mime_type" );
466                         print $this->image->getImageBlob();
467
468                         // Reset Image to original Format
469                         $this->image->setImageFormat( $this->get_extension( $this->mime_type ) );
470                 }
471                 catch ( Exception $e ) {
472                         return new WP_Error( 'image_stream_error', $e->getMessage() );
473                 }
474
475                 return true;
476         }
477 }