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