]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/class-wp-image-editor-gd.php
WordPress 4.6.3-scripts
[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                 // Set artificially high because GD uses uncompressed images in memory.
100                 wp_raise_memory_limit( 'image' );
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          * @return true
131          */
132         protected function update_size( $width = false, $height = false ) {
133                 if ( ! $width )
134                         $width = imagesx( $this->image );
135
136                 if ( ! $height )
137                         $height = imagesy( $this->image );
138
139                 return parent::update_size( $width, $height );
140         }
141
142         /**
143          * Resizes current image.
144          * Wraps _resize, since _resize returns a GD Resource.
145          *
146          * At minimum, either a height or width must be provided.
147          * If one of the two is set to null, the resize will
148          * maintain aspect ratio according to the provided dimension.
149          *
150          * @since 3.5.0
151          * @access public
152          *
153          * @param  int|null $max_w Image width.
154          * @param  int|null $max_h Image height.
155          * @param  bool     $crop
156          * @return true|WP_Error
157          */
158         public function resize( $max_w, $max_h, $crop = false ) {
159                 if ( ( $this->size['width'] == $max_w ) && ( $this->size['height'] == $max_h ) )
160                         return true;
161
162                 $resized = $this->_resize( $max_w, $max_h, $crop );
163
164                 if ( is_resource( $resized ) ) {
165                         imagedestroy( $this->image );
166                         $this->image = $resized;
167                         return true;
168
169                 } elseif ( is_wp_error( $resized ) )
170                         return $resized;
171
172                 return new WP_Error( 'image_resize_error', __('Image resize failed.'), $this->file );
173         }
174
175         /**
176          *
177          * @param int $max_w
178          * @param int $max_h
179          * @param bool|array $crop
180          * @return resource|WP_Error
181          */
182         protected function _resize( $max_w, $max_h, $crop = false ) {
183                 $dims = image_resize_dimensions( $this->size['width'], $this->size['height'], $max_w, $max_h, $crop );
184                 if ( ! $dims ) {
185                         return new WP_Error( 'error_getting_dimensions', __('Could not calculate resized image dimensions'), $this->file );
186                 }
187                 list( $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h ) = $dims;
188
189                 $resized = wp_imagecreatetruecolor( $dst_w, $dst_h );
190                 imagecopyresampled( $resized, $this->image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h );
191
192                 if ( is_resource( $resized ) ) {
193                         $this->update_size( $dst_w, $dst_h );
194                         return $resized;
195                 }
196
197                 return new WP_Error( 'image_resize_error', __('Image resize failed.'), $this->file );
198         }
199
200         /**
201          * Resize multiple images from a single source.
202          *
203          * @since 3.5.0
204          * @access public
205          *
206          * @param array $sizes {
207          *     An array of image size arrays. Default sizes are 'small', 'medium', 'medium_large', 'large'.
208          *
209          *     Either a height or width must be provided.
210          *     If one of the two is set to null, the resize will
211          *     maintain aspect ratio according to the provided dimension.
212          *
213          *     @type array $size {
214          *         Array of height, width values, and whether to crop.
215          *
216          *         @type int  $width  Image width. Optional if `$height` is specified.
217          *         @type int  $height Image height. Optional if `$width` is specified.
218          *         @type bool $crop   Optional. Whether to crop the image. Default false.
219          *     }
220          * }
221          * @return array An array of resized images' metadata by size.
222          */
223         public function multi_resize( $sizes ) {
224                 $metadata = array();
225                 $orig_size = $this->size;
226
227                 foreach ( $sizes as $size => $size_data ) {
228                         if ( ! isset( $size_data['width'] ) && ! isset( $size_data['height'] ) ) {
229                                 continue;
230                         }
231
232                         if ( ! isset( $size_data['width'] ) ) {
233                                 $size_data['width'] = null;
234                         }
235                         if ( ! isset( $size_data['height'] ) ) {
236                                 $size_data['height'] = null;
237                         }
238
239                         if ( ! isset( $size_data['crop'] ) ) {
240                                 $size_data['crop'] = false;
241                         }
242
243                         $image = $this->_resize( $size_data['width'], $size_data['height'], $size_data['crop'] );
244                         $duplicate = ( ( $orig_size['width'] == $size_data['width'] ) && ( $orig_size['height'] == $size_data['height'] ) );
245
246                         if ( ! is_wp_error( $image ) && ! $duplicate ) {
247                                 $resized = $this->_save( $image );
248
249                                 imagedestroy( $image );
250
251                                 if ( ! is_wp_error( $resized ) && $resized ) {
252                                         unset( $resized['path'] );
253                                         $metadata[$size] = $resized;
254                                 }
255                         }
256
257                         $this->size = $orig_size;
258                 }
259
260                 return $metadata;
261         }
262
263         /**
264          * Crops Image.
265          *
266          * @since 3.5.0
267          * @access public
268          *
269          * @param int  $src_x   The start x position to crop from.
270          * @param int  $src_y   The start y position to crop from.
271          * @param int  $src_w   The width to crop.
272          * @param int  $src_h   The height to crop.
273          * @param int  $dst_w   Optional. The destination width.
274          * @param int  $dst_h   Optional. The destination height.
275          * @param bool $src_abs Optional. If the source crop points are absolute.
276          * @return bool|WP_Error
277          */
278         public function crop( $src_x, $src_y, $src_w, $src_h, $dst_w = null, $dst_h = null, $src_abs = false ) {
279                 // If destination width/height isn't specified, use same as
280                 // width/height from source.
281                 if ( ! $dst_w )
282                         $dst_w = $src_w;
283                 if ( ! $dst_h )
284                         $dst_h = $src_h;
285
286                 $dst = wp_imagecreatetruecolor( $dst_w, $dst_h );
287
288                 if ( $src_abs ) {
289                         $src_w -= $src_x;
290                         $src_h -= $src_y;
291                 }
292
293                 if ( function_exists( 'imageantialias' ) )
294                         imageantialias( $dst, true );
295
296                 imagecopyresampled( $dst, $this->image, 0, 0, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h );
297
298                 if ( is_resource( $dst ) ) {
299                         imagedestroy( $this->image );
300                         $this->image = $dst;
301                         $this->update_size();
302                         return true;
303                 }
304
305                 return new WP_Error( 'image_crop_error', __('Image crop failed.'), $this->file );
306         }
307
308         /**
309          * Rotates current image counter-clockwise by $angle.
310          * Ported from image-edit.php
311          *
312          * @since 3.5.0
313          * @access public
314          *
315          * @param float $angle
316          * @return true|WP_Error
317          */
318         public function rotate( $angle ) {
319                 if ( function_exists('imagerotate') ) {
320                         $transparency = imagecolorallocatealpha( $this->image, 255, 255, 255, 127 );
321                         $rotated = imagerotate( $this->image, $angle, $transparency );
322
323                         if ( is_resource( $rotated ) ) {
324                                 imagealphablending( $rotated, true );
325                                 imagesavealpha( $rotated, true );
326                                 imagedestroy( $this->image );
327                                 $this->image = $rotated;
328                                 $this->update_size();
329                                 return true;
330                         }
331                 }
332                 return new WP_Error( 'image_rotate_error', __('Image rotate failed.'), $this->file );
333         }
334
335         /**
336          * Flips current image.
337          *
338          * @since 3.5.0
339          * @access public
340          *
341          * @param bool $horz Flip along Horizontal Axis
342          * @param bool $vert Flip along Vertical Axis
343          * @return true|WP_Error
344          */
345         public function flip( $horz, $vert ) {
346                 $w = $this->size['width'];
347                 $h = $this->size['height'];
348                 $dst = wp_imagecreatetruecolor( $w, $h );
349
350                 if ( is_resource( $dst ) ) {
351                         $sx = $vert ? ($w - 1) : 0;
352                         $sy = $horz ? ($h - 1) : 0;
353                         $sw = $vert ? -$w : $w;
354                         $sh = $horz ? -$h : $h;
355
356                         if ( imagecopyresampled( $dst, $this->image, 0, 0, $sx, $sy, $w, $h, $sw, $sh ) ) {
357                                 imagedestroy( $this->image );
358                                 $this->image = $dst;
359                                 return true;
360                         }
361                 }
362                 return new WP_Error( 'image_flip_error', __('Image flip failed.'), $this->file );
363         }
364
365         /**
366          * Saves current in-memory image to file.
367          *
368          * @since 3.5.0
369          * @access public
370          *
371          * @param string|null $filename
372          * @param string|null $mime_type
373          * @return array|WP_Error {'path'=>string, 'file'=>string, 'width'=>int, 'height'=>int, 'mime-type'=>string}
374          */
375         public function save( $filename = null, $mime_type = null ) {
376                 $saved = $this->_save( $this->image, $filename, $mime_type );
377
378                 if ( ! is_wp_error( $saved ) ) {
379                         $this->file = $saved['path'];
380                         $this->mime_type = $saved['mime-type'];
381                 }
382
383                 return $saved;
384         }
385
386         /**
387          * @param resource $image
388          * @param string|null $filename
389          * @param string|null $mime_type
390          * @return WP_Error|array
391          */
392         protected function _save( $image, $filename = null, $mime_type = null ) {
393                 list( $filename, $extension, $mime_type ) = $this->get_output_format( $filename, $mime_type );
394
395                 if ( ! $filename )
396                         $filename = $this->generate_filename( null, null, $extension );
397
398                 if ( 'image/gif' == $mime_type ) {
399                         if ( ! $this->make_image( $filename, 'imagegif', array( $image, $filename ) ) )
400                                 return new WP_Error( 'image_save_error', __('Image Editor Save Failed') );
401                 }
402                 elseif ( 'image/png' == $mime_type ) {
403                         // convert from full colors to index colors, like original PNG.
404                         if ( function_exists('imageistruecolor') && ! imageistruecolor( $image ) )
405                                 imagetruecolortopalette( $image, false, imagecolorstotal( $image ) );
406
407                         if ( ! $this->make_image( $filename, 'imagepng', array( $image, $filename ) ) )
408                                 return new WP_Error( 'image_save_error', __('Image Editor Save Failed') );
409                 }
410                 elseif ( 'image/jpeg' == $mime_type ) {
411                         if ( ! $this->make_image( $filename, 'imagejpeg', array( $image, $filename, $this->get_quality() ) ) )
412                                 return new WP_Error( 'image_save_error', __('Image Editor Save Failed') );
413                 }
414                 else {
415                         return new WP_Error( 'image_save_error', __('Image Editor Save Failed') );
416                 }
417
418                 // Set correct file permissions
419                 $stat = stat( dirname( $filename ) );
420                 $perms = $stat['mode'] & 0000666; //same permissions as parent folder, strip off the executable bits
421                 @ chmod( $filename, $perms );
422
423                 /**
424                  * Filters the name of the saved image file.
425                  *
426                  * @since 2.6.0
427                  *
428                  * @param string $filename Name of the file.
429                  */
430                 return array(
431                         'path'      => $filename,
432                         'file'      => wp_basename( apply_filters( 'image_make_intermediate_size', $filename ) ),
433                         'width'     => $this->size['width'],
434                         'height'    => $this->size['height'],
435                         'mime-type' => $mime_type,
436                 );
437         }
438
439         /**
440          * Returns stream of current image.
441          *
442          * @since 3.5.0
443          * @access public
444          *
445          * @param string $mime_type
446          * @return bool
447          */
448         public function stream( $mime_type = null ) {
449                 list( $filename, $extension, $mime_type ) = $this->get_output_format( null, $mime_type );
450
451                 switch ( $mime_type ) {
452                         case 'image/png':
453                                 header( 'Content-Type: image/png' );
454                                 return imagepng( $this->image );
455                         case 'image/gif':
456                                 header( 'Content-Type: image/gif' );
457                                 return imagegif( $this->image );
458                         default:
459                                 header( 'Content-Type: image/jpeg' );
460                                 return imagejpeg( $this->image, null, $this->get_quality() );
461                 }
462         }
463
464         /**
465          * Either calls editor's save function or handles file as a stream.
466          *
467          * @since 3.5.0
468          * @access protected
469          *
470          * @param string|stream $filename
471          * @param callable $function
472          * @param array $arguments
473          * @return bool
474          */
475         protected function make_image( $filename, $function, $arguments ) {
476                 if ( wp_is_stream( $filename ) )
477                         $arguments[1] = null;
478
479                 return parent::make_image( $filename, $function, $arguments );
480         }
481 }