]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/class-wp-image-editor-gd.php
WordPress 3.9
[autoinstalls/wordpress.git] / wp-includes / class-wp-image-editor-gd.php
1 <?php
2 /**
3  * WordPress GD Image Editor
4  *
5  * @package WordPress
6  * @subpackage Image_Editor
7  */
8
9 /**
10  * WordPress Image Editor Class for Image Manipulation through GD
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_GD extends WP_Image_Editor {
18
19         protected $image = false; // GD Resource
20
21         function __destruct() {
22                 if ( $this->image ) {
23                         // we don't need the original in memory anymore
24                         imagedestroy( $this->image );
25                 }
26         }
27
28         /**
29          * Checks to see if current environment supports GD.
30          *
31          * @since 3.5.0
32          * @access public
33          *
34          * @return boolean
35          */
36         public static function test( $args = array() ) {
37                 if ( ! extension_loaded('gd') || ! function_exists('gd_info') )
38                         return false;
39
40                 // On some setups GD library does not provide imagerotate() - Ticket #11536
41                 if ( isset( $args['methods'] ) &&
42                          in_array( 'rotate', $args['methods'] ) &&
43                          ! function_exists('imagerotate') ){
44
45                                 return false;
46                 }
47
48                 return true;
49         }
50
51         /**
52          * Checks to see if editor supports the mime-type specified.
53          *
54          * @since 3.5.0
55          * @access public
56          *
57          * @param string $mime_type
58          * @return boolean
59          */
60         public static function supports_mime_type( $mime_type ) {
61                 $image_types = imagetypes();
62                 switch( $mime_type ) {
63                         case 'image/jpeg':
64                                 return ($image_types & IMG_JPG) != 0;
65                         case 'image/png':
66                                 return ($image_types & IMG_PNG) != 0;
67                         case 'image/gif':
68                                 return ($image_types & IMG_GIF) != 0;
69                 }
70
71                 return false;
72         }
73
74         /**
75          * Loads image from $this->file into new GD Resource.
76          *
77          * @since 3.5.0
78          * @access protected
79          *
80          * @return boolean|WP_Error True if loaded successfully; WP_Error on failure.
81          */
82         public function load() {
83                 if ( $this->image )
84                         return true;
85
86                 if ( ! is_file( $this->file ) && ! preg_match( '|^https?://|', $this->file ) )
87                         return new WP_Error( 'error_loading_image', __('File doesn&#8217;t exist?'), $this->file );
88
89                 /**
90                  * Filter the memory limit allocated for image manipulation.
91                  *
92                  * @since 3.5.0
93                  *
94                  * @param int|string $limit Maximum memory limit to allocate for images. Default WP_MAX_MEMORY_LIMIT.
95                  *                          Accepts an integer (bytes), or a shorthand string notation, such as '256M'.
96                  */
97                 // Set artificially high because GD uses uncompressed images in memory
98                 @ini_set( 'memory_limit', apply_filters( 'image_memory_limit', WP_MAX_MEMORY_LIMIT ) );
99
100                 $this->image = @imagecreatefromstring( file_get_contents( $this->file ) );
101
102                 if ( ! is_resource( $this->image ) )
103                         return new WP_Error( 'invalid_image', __('File is not an image.'), $this->file );
104
105                 $size = @getimagesize( $this->file );
106                 if ( ! $size )
107                         return new WP_Error( 'invalid_image', __('Could not read image size.'), $this->file );
108
109                 if ( function_exists( 'imagealphablending' ) && function_exists( 'imagesavealpha' ) ) {
110                         imagealphablending( $this->image, false );
111                         imagesavealpha( $this->image, true );
112                 }
113
114                 $this->update_size( $size[0], $size[1] );
115                 $this->mime_type = $size['mime'];
116
117                 return $this->set_quality( $this->quality );
118         }
119
120         /**
121          * Sets or updates current image size.
122          *
123          * @since 3.5.0
124          * @access protected
125          *
126          * @param int $width
127          * @param int $height
128          */
129         protected function update_size( $width = false, $height = false ) {
130                 if ( ! $width )
131                         $width = imagesx( $this->image );
132
133                 if ( ! $height )
134                         $height = imagesy( $this->image );
135
136                 return parent::update_size( $width, $height );
137         }
138
139         /**
140          * Resizes current image.
141          * Wraps _resize, since _resize returns a GD Resource.
142          *
143          * At minimum, either a height or width must be provided.
144          * If one of the two is set to null, the resize will
145          * maintain aspect ratio according to the provided dimension.
146          *
147          * @since 3.5.0
148          * @access public
149          *
150          * @param  int|null $max_w Image width.
151          * @param  int|null $max_h Image height.
152          * @param  boolean  $crop
153          * @return boolean|WP_Error
154          */
155         public function resize( $max_w, $max_h, $crop = false ) {
156                 if ( ( $this->size['width'] == $max_w ) && ( $this->size['height'] == $max_h ) )
157                         return true;
158
159                 $resized = $this->_resize( $max_w, $max_h, $crop );
160
161                 if ( is_resource( $resized ) ) {
162                         imagedestroy( $this->image );
163                         $this->image = $resized;
164                         return true;
165
166                 } elseif ( is_wp_error( $resized ) )
167                         return $resized;
168
169                 return new WP_Error( 'image_resize_error', __('Image resize failed.'), $this->file );
170         }
171
172         protected function _resize( $max_w, $max_h, $crop = false ) {
173                 $dims = image_resize_dimensions( $this->size['width'], $this->size['height'], $max_w, $max_h, $crop );
174                 if ( ! $dims ) {
175                         return new WP_Error( 'error_getting_dimensions', __('Could not calculate resized image dimensions'), $this->file );
176                 }
177                 list( $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h ) = $dims;
178
179                 $resized = wp_imagecreatetruecolor( $dst_w, $dst_h );
180                 imagecopyresampled( $resized, $this->image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h );
181
182                 if ( is_resource( $resized ) ) {
183                         $this->update_size( $dst_w, $dst_h );
184                         return $resized;
185                 }
186
187                 return new WP_Error( 'image_resize_error', __('Image resize failed.'), $this->file );
188         }
189
190         /**
191          * Resize multiple images from a single source.
192          *
193          * @since 3.5.0
194          * @access public
195          *
196          * @param array $sizes {
197          *     An array of image size arrays. Default sizes are 'small', 'medium', 'large'.
198          *
199          *     Either a height or width must be provided.
200          *     If one of the two is set to null, the resize will
201          *     maintain aspect ratio according to the provided dimension.
202          *
203          *     @type array $size {
204          *         @type int  ['width']  Optional. Image width.
205          *         @type int  ['height'] Optional. Image height.
206          *         @type bool ['crop']   Optional. Whether to crop the image. Default false.
207          *     }
208          * }
209          * @return array An array of resized images' metadata by size.
210          */
211         public function multi_resize( $sizes ) {
212                 $metadata = array();
213                 $orig_size = $this->size;
214
215                 foreach ( $sizes as $size => $size_data ) {
216                         if ( ! isset( $size_data['width'] ) && ! isset( $size_data['height'] ) ) {
217                                 continue;
218                         }
219
220                         if ( ! isset( $size_data['width'] ) ) {
221                                 $size_data['width'] = null;
222                         }
223                         if ( ! isset( $size_data['height'] ) ) {
224                                 $size_data['height'] = null;
225                         }
226
227                         if ( ! isset( $size_data['crop'] ) ) {
228                                 $size_data['crop'] = false;
229                         }
230
231                         $image = $this->_resize( $size_data['width'], $size_data['height'], $size_data['crop'] );
232
233                         if( ! is_wp_error( $image ) ) {
234                                 $resized = $this->_save( $image );
235
236                                 imagedestroy( $image );
237
238                                 if ( ! is_wp_error( $resized ) && $resized ) {
239                                         unset( $resized['path'] );
240                                         $metadata[$size] = $resized;
241                                 }
242                         }
243
244                         $this->size = $orig_size;
245                 }
246
247                 return $metadata;
248         }
249
250         /**
251          * Crops Image.
252          *
253          * @since 3.5.0
254          * @access public
255          *
256          * @param string|int $src The source file or Attachment ID.
257          * @param int $src_x The start x position to crop from.
258          * @param int $src_y The start y position to crop from.
259          * @param int $src_w The width to crop.
260          * @param int $src_h The height to crop.
261          * @param int $dst_w Optional. The destination width.
262          * @param int $dst_h Optional. The destination height.
263          * @param boolean $src_abs Optional. If the source crop points are absolute.
264          * @return boolean|WP_Error
265          */
266         public function crop( $src_x, $src_y, $src_w, $src_h, $dst_w = null, $dst_h = null, $src_abs = false ) {
267                 // If destination width/height isn't specified, use same as
268                 // width/height from source.
269                 if ( ! $dst_w )
270                         $dst_w = $src_w;
271                 if ( ! $dst_h )
272                         $dst_h = $src_h;
273
274                 $dst = wp_imagecreatetruecolor( $dst_w, $dst_h );
275
276                 if ( $src_abs ) {
277                         $src_w -= $src_x;
278                         $src_h -= $src_y;
279                 }
280
281                 if ( function_exists( 'imageantialias' ) )
282                         imageantialias( $dst, true );
283
284                 imagecopyresampled( $dst, $this->image, 0, 0, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h );
285
286                 if ( is_resource( $dst ) ) {
287                         imagedestroy( $this->image );
288                         $this->image = $dst;
289                         $this->update_size();
290                         return true;
291                 }
292
293                 return new WP_Error( 'image_crop_error', __('Image crop failed.'), $this->file );
294         }
295
296         /**
297          * Rotates current image counter-clockwise by $angle.
298          * Ported from image-edit.php
299          *
300          * @since 3.5.0
301          * @access public
302          *
303          * @param float $angle
304          * @return boolean|WP_Error
305          */
306         public function rotate( $angle ) {
307                 if ( function_exists('imagerotate') ) {
308                         $rotated = imagerotate( $this->image, $angle, 0 );
309
310                         if ( is_resource( $rotated ) ) {
311                                 imagedestroy( $this->image );
312                                 $this->image = $rotated;
313                                 $this->update_size();
314                                 return true;
315                         }
316                 }
317                 return new WP_Error( 'image_rotate_error', __('Image rotate failed.'), $this->file );
318         }
319
320         /**
321          * Flips current image.
322          *
323          * @since 3.5.0
324          * @access public
325          *
326          * @param boolean $horz Flip along Horizontal Axis
327          * @param boolean $vert Flip along Vertical Axis
328          * @returns boolean|WP_Error
329          */
330         public function flip( $horz, $vert ) {
331                 $w = $this->size['width'];
332                 $h = $this->size['height'];
333                 $dst = wp_imagecreatetruecolor( $w, $h );
334
335                 if ( is_resource( $dst ) ) {
336                         $sx = $vert ? ($w - 1) : 0;
337                         $sy = $horz ? ($h - 1) : 0;
338                         $sw = $vert ? -$w : $w;
339                         $sh = $horz ? -$h : $h;
340
341                         if ( imagecopyresampled( $dst, $this->image, 0, 0, $sx, $sy, $w, $h, $sw, $sh ) ) {
342                                 imagedestroy( $this->image );
343                                 $this->image = $dst;
344                                 return true;
345                         }
346                 }
347                 return new WP_Error( 'image_flip_error', __('Image flip failed.'), $this->file );
348         }
349
350         /**
351          * Saves current in-memory image to file.
352          *
353          * @since 3.5.0
354          * @access public
355          *
356          * @param string $destfilename
357          * @param string $mime_type
358          * @return array|WP_Error {'path'=>string, 'file'=>string, 'width'=>int, 'height'=>int, 'mime-type'=>string}
359          */
360         public function save( $filename = null, $mime_type = null ) {
361                 $saved = $this->_save( $this->image, $filename, $mime_type );
362
363                 if ( ! is_wp_error( $saved ) ) {
364                         $this->file = $saved['path'];
365                         $this->mime_type = $saved['mime-type'];
366                 }
367
368                 return $saved;
369         }
370
371         protected function _save( $image, $filename = null, $mime_type = null ) {
372                 list( $filename, $extension, $mime_type ) = $this->get_output_format( $filename, $mime_type );
373
374                 if ( ! $filename )
375                         $filename = $this->generate_filename( null, null, $extension );
376
377                 if ( 'image/gif' == $mime_type ) {
378                         if ( ! $this->make_image( $filename, 'imagegif', array( $image, $filename ) ) )
379                                 return new WP_Error( 'image_save_error', __('Image Editor Save Failed') );
380                 }
381                 elseif ( 'image/png' == $mime_type ) {
382                         // convert from full colors to index colors, like original PNG.
383                         if ( function_exists('imageistruecolor') && ! imageistruecolor( $image ) )
384                                 imagetruecolortopalette( $image, false, imagecolorstotal( $image ) );
385
386                         if ( ! $this->make_image( $filename, 'imagepng', array( $image, $filename ) ) )
387                                 return new WP_Error( 'image_save_error', __('Image Editor Save Failed') );
388                 }
389                 elseif ( 'image/jpeg' == $mime_type ) {
390                         if ( ! $this->make_image( $filename, 'imagejpeg', array( $image, $filename, $this->quality ) ) )
391                                 return new WP_Error( 'image_save_error', __('Image Editor Save Failed') );
392                 }
393                 else {
394                         return new WP_Error( 'image_save_error', __('Image Editor Save Failed') );
395                 }
396
397                 // Set correct file permissions
398                 $stat = stat( dirname( $filename ) );
399                 $perms = $stat['mode'] & 0000666; //same permissions as parent folder, strip off the executable bits
400                 @ chmod( $filename, $perms );
401
402                 /**
403                  * Filter the name of the saved image file.
404                  *
405                  * @since 2.6.0
406                  *
407                  * @param string $filename Name of the file.
408                  */
409                 return array(
410                         'path'      => $filename,
411                         'file'      => wp_basename( apply_filters( 'image_make_intermediate_size', $filename ) ),
412                         'width'     => $this->size['width'],
413                         'height'    => $this->size['height'],
414                         'mime-type' => $mime_type,
415                 );
416         }
417
418         /**
419          * Returns stream of current image.
420          *
421          * @since 3.5.0
422          * @access public
423          *
424          * @param string $mime_type
425          */
426         public function stream( $mime_type = null ) {
427                 list( $filename, $extension, $mime_type ) = $this->get_output_format( null, $mime_type );
428
429                 switch ( $mime_type ) {
430                         case 'image/png':
431                                 header( 'Content-Type: image/png' );
432                                 return imagepng( $this->image );
433                         case 'image/gif':
434                                 header( 'Content-Type: image/gif' );
435                                 return imagegif( $this->image );
436                         default:
437                                 header( 'Content-Type: image/jpeg' );
438                                 return imagejpeg( $this->image, null, $this->quality );
439                 }
440         }
441
442         /**
443          * Either calls editor's save function or handles file as a stream.
444          *
445          * @since 3.5.0
446          * @access protected
447          *
448          * @param string|stream $filename
449          * @param callable $function
450          * @param array $arguments
451          * @return boolean
452          */
453         protected function make_image( $filename, $function, $arguments ) {
454                 if ( wp_is_stream( $filename ) )
455                         $arguments[1] = null;
456
457                 return parent::make_image( $filename, $function, $arguments );
458         }
459 }