[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

/wp-includes/ -> class-wp-image-editor-gd.php (source)

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


Generated: Wed Sep 18 01:00:03 2019 Cross-referenced by PHPXref 0.7.1