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