[ 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 {
 249       *     Array of size data.
 250       *
 251       *     @type int  $width  The maximum width in pixels.
 252       *     @type int  $height The maximum height in pixels.
 253       *     @type bool $crop   Whether to crop the image to exact dimensions.
 254       * }
 255       * @return array|WP_Error The image data array for inclusion in the `sizes` array in the image meta,
 256       *                        WP_Error object on error.
 257       */
 258  	public function make_subsize( $size_data ) {
 259          if ( ! isset( $size_data['width'] ) && ! isset( $size_data['height'] ) ) {
 260              return new WP_Error( 'image_subsize_create_error', __( 'Cannot resize the image. Both width and height are not set.' ) );
 261          }
 262  
 263          $orig_size = $this->size;
 264  
 265          if ( ! isset( $size_data['width'] ) ) {
 266              $size_data['width'] = null;
 267          }
 268  
 269          if ( ! isset( $size_data['height'] ) ) {
 270              $size_data['height'] = null;
 271          }
 272  
 273          if ( ! isset( $size_data['crop'] ) ) {
 274              $size_data['crop'] = false;
 275          }
 276  
 277          $resized = $this->_resize( $size_data['width'], $size_data['height'], $size_data['crop'] );
 278  
 279          if ( is_wp_error( $resized ) ) {
 280              $saved = $resized;
 281          } else {
 282              $saved = $this->_save( $resized );
 283              imagedestroy( $resized );
 284          }
 285  
 286          $this->size = $orig_size;
 287  
 288          if ( ! is_wp_error( $saved ) ) {
 289              unset( $saved['path'] );
 290          }
 291  
 292          return $saved;
 293      }
 294  
 295      /**
 296       * Crops Image.
 297       *
 298       * @since 3.5.0
 299       *
 300       * @param int  $src_x   The start x position to crop from.
 301       * @param int  $src_y   The start y position to crop from.
 302       * @param int  $src_w   The width to crop.
 303       * @param int  $src_h   The height to crop.
 304       * @param int  $dst_w   Optional. The destination width.
 305       * @param int  $dst_h   Optional. The destination height.
 306       * @param bool $src_abs Optional. If the source crop points are absolute.
 307       * @return bool|WP_Error
 308       */
 309  	public function crop( $src_x, $src_y, $src_w, $src_h, $dst_w = null, $dst_h = null, $src_abs = false ) {
 310          // If destination width/height isn't specified,
 311          // use same as width/height from source.
 312          if ( ! $dst_w ) {
 313              $dst_w = $src_w;
 314          }
 315          if ( ! $dst_h ) {
 316              $dst_h = $src_h;
 317          }
 318  
 319          $dst = wp_imagecreatetruecolor( $dst_w, $dst_h );
 320  
 321          if ( $src_abs ) {
 322              $src_w -= $src_x;
 323              $src_h -= $src_y;
 324          }
 325  
 326          if ( function_exists( 'imageantialias' ) ) {
 327              imageantialias( $dst, true );
 328          }
 329  
 330          imagecopyresampled( $dst, $this->image, 0, 0, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h );
 331  
 332          if ( is_resource( $dst ) ) {
 333              imagedestroy( $this->image );
 334              $this->image = $dst;
 335              $this->update_size();
 336              return true;
 337          }
 338  
 339          return new WP_Error( 'image_crop_error', __( 'Image crop failed.' ), $this->file );
 340      }
 341  
 342      /**
 343       * Rotates current image counter-clockwise by $angle.
 344       * Ported from image-edit.php
 345       *
 346       * @since 3.5.0
 347       *
 348       * @param float $angle
 349       * @return true|WP_Error
 350       */
 351  	public function rotate( $angle ) {
 352          if ( function_exists( 'imagerotate' ) ) {
 353              $transparency = imagecolorallocatealpha( $this->image, 255, 255, 255, 127 );
 354              $rotated      = imagerotate( $this->image, $angle, $transparency );
 355  
 356              if ( is_resource( $rotated ) ) {
 357                  imagealphablending( $rotated, true );
 358                  imagesavealpha( $rotated, true );
 359                  imagedestroy( $this->image );
 360                  $this->image = $rotated;
 361                  $this->update_size();
 362                  return true;
 363              }
 364          }
 365          return new WP_Error( 'image_rotate_error', __( 'Image rotate failed.' ), $this->file );
 366      }
 367  
 368      /**
 369       * Flips current image.
 370       *
 371       * @since 3.5.0
 372       *
 373       * @param bool $horz Flip along Horizontal Axis.
 374       * @param bool $vert Flip along Vertical Axis.
 375       * @return true|WP_Error
 376       */
 377  	public function flip( $horz, $vert ) {
 378          $w   = $this->size['width'];
 379          $h   = $this->size['height'];
 380          $dst = wp_imagecreatetruecolor( $w, $h );
 381  
 382          if ( is_resource( $dst ) ) {
 383              $sx = $vert ? ( $w - 1 ) : 0;
 384              $sy = $horz ? ( $h - 1 ) : 0;
 385              $sw = $vert ? -$w : $w;
 386              $sh = $horz ? -$h : $h;
 387  
 388              if ( imagecopyresampled( $dst, $this->image, 0, 0, $sx, $sy, $w, $h, $sw, $sh ) ) {
 389                  imagedestroy( $this->image );
 390                  $this->image = $dst;
 391                  return true;
 392              }
 393          }
 394          return new WP_Error( 'image_flip_error', __( 'Image flip failed.' ), $this->file );
 395      }
 396  
 397      /**
 398       * Saves current in-memory image to file.
 399       *
 400       * @since 3.5.0
 401       *
 402       * @param string|null $filename
 403       * @param string|null $mime_type
 404       * @return array|WP_Error {'path'=>string, 'file'=>string, 'width'=>int, 'height'=>int, 'mime-type'=>string}
 405       */
 406  	public function save( $filename = null, $mime_type = null ) {
 407          $saved = $this->_save( $this->image, $filename, $mime_type );
 408  
 409          if ( ! is_wp_error( $saved ) ) {
 410              $this->file      = $saved['path'];
 411              $this->mime_type = $saved['mime-type'];
 412          }
 413  
 414          return $saved;
 415      }
 416  
 417      /**
 418       * @param resource $image
 419       * @param string|null $filename
 420       * @param string|null $mime_type
 421       * @return array|WP_Error
 422       */
 423  	protected function _save( $image, $filename = null, $mime_type = null ) {
 424          list( $filename, $extension, $mime_type ) = $this->get_output_format( $filename, $mime_type );
 425  
 426          if ( ! $filename ) {
 427              $filename = $this->generate_filename( null, null, $extension );
 428          }
 429  
 430          if ( 'image/gif' === $mime_type ) {
 431              if ( ! $this->make_image( $filename, 'imagegif', array( $image, $filename ) ) ) {
 432                  return new WP_Error( 'image_save_error', __( 'Image Editor Save Failed' ) );
 433              }
 434          } elseif ( 'image/png' === $mime_type ) {
 435              // Convert from full colors to index colors, like original PNG.
 436              if ( function_exists( 'imageistruecolor' ) && ! imageistruecolor( $image ) ) {
 437                  imagetruecolortopalette( $image, false, imagecolorstotal( $image ) );
 438              }
 439  
 440              if ( ! $this->make_image( $filename, 'imagepng', array( $image, $filename ) ) ) {
 441                  return new WP_Error( 'image_save_error', __( 'Image Editor Save Failed' ) );
 442              }
 443          } elseif ( 'image/jpeg' === $mime_type ) {
 444              if ( ! $this->make_image( $filename, 'imagejpeg', array( $image, $filename, $this->get_quality() ) ) ) {
 445                  return new WP_Error( 'image_save_error', __( 'Image Editor Save Failed' ) );
 446              }
 447          } else {
 448              return new WP_Error( 'image_save_error', __( 'Image Editor Save Failed' ) );
 449          }
 450  
 451          // Set correct file permissions.
 452          $stat  = stat( dirname( $filename ) );
 453          $perms = $stat['mode'] & 0000666; // Same permissions as parent folder, strip off the executable bits.
 454          chmod( $filename, $perms );
 455  
 456          /**
 457           * Filters the name of the saved image file.
 458           *
 459           * @since 2.6.0
 460           *
 461           * @param string $filename Name of the file.
 462           */
 463          return array(
 464              'path'      => $filename,
 465              'file'      => wp_basename( apply_filters( 'image_make_intermediate_size', $filename ) ),
 466              'width'     => $this->size['width'],
 467              'height'    => $this->size['height'],
 468              'mime-type' => $mime_type,
 469          );
 470      }
 471  
 472      /**
 473       * Returns stream of current image.
 474       *
 475       * @since 3.5.0
 476       *
 477       * @param string $mime_type The mime type of the image.
 478       * @return bool True on success, false on failure.
 479       */
 480  	public function stream( $mime_type = null ) {
 481          list( $filename, $extension, $mime_type ) = $this->get_output_format( null, $mime_type );
 482  
 483          switch ( $mime_type ) {
 484              case 'image/png':
 485                  header( 'Content-Type: image/png' );
 486                  return imagepng( $this->image );
 487              case 'image/gif':
 488                  header( 'Content-Type: image/gif' );
 489                  return imagegif( $this->image );
 490              default:
 491                  header( 'Content-Type: image/jpeg' );
 492                  return imagejpeg( $this->image, null, $this->get_quality() );
 493          }
 494      }
 495  
 496      /**
 497       * Either calls editor's save function or handles file as a stream.
 498       *
 499       * @since 3.5.0
 500       *
 501       * @param string|stream $filename
 502       * @param callable $function
 503       * @param array $arguments
 504       * @return bool
 505       */
 506  	protected function make_image( $filename, $function, $arguments ) {
 507          if ( wp_is_stream( $filename ) ) {
 508              $arguments[1] = null;
 509          }
 510  
 511          return parent::make_image( $filename, $function, $arguments );
 512      }
 513  }


Generated: Wed Feb 26 01:00:04 2020 Cross-referenced by PHPXref 0.7.1