[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

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|GdImage
  21       */
  22      protected $image;
  23  
  24  	public function __destruct() {
  25          if ( $this->image ) {
  26              if ( PHP_VERSION_ID < 80000 ) { // imagedestroy() has no effect as of PHP 8.0.
  27                  // We don't need the original in memory anymore.
  28                  imagedestroy( $this->image );
  29              }
  30          }
  31      }
  32  
  33      /**
  34       * Checks to see if current environment supports GD.
  35       *
  36       * @since 3.5.0
  37       *
  38       * @param array $args
  39       * @return bool
  40       */
  41  	public static function test( $args = array() ) {
  42          if ( ! extension_loaded( 'gd' ) || ! function_exists( 'gd_info' ) ) {
  43              return false;
  44          }
  45  
  46          // On some setups GD library does not provide imagerotate() - Ticket #11536.
  47          if ( isset( $args['methods'] ) &&
  48              in_array( 'rotate', $args['methods'], true ) &&
  49              ! function_exists( 'imagerotate' ) ) {
  50  
  51                  return false;
  52          }
  53  
  54          return true;
  55      }
  56  
  57      /**
  58       * Checks to see if editor supports the mime-type specified.
  59       *
  60       * @since 3.5.0
  61       *
  62       * @param string $mime_type
  63       * @return bool
  64       */
  65  	public static function supports_mime_type( $mime_type ) {
  66          $image_types = imagetypes();
  67          switch ( $mime_type ) {
  68              case 'image/jpeg':
  69                  return ( $image_types & IMG_JPG ) !== 0;
  70              case 'image/png':
  71                  return ( $image_types & IMG_PNG ) !== 0;
  72              case 'image/gif':
  73                  return ( $image_types & IMG_GIF ) !== 0;
  74              case 'image/webp':
  75                  return ( $image_types & IMG_WEBP ) !== 0;
  76              case 'image/avif':
  77                  return ( $image_types & IMG_AVIF ) !== 0 && function_exists( 'imageavif' );
  78          }
  79  
  80          return false;
  81      }
  82  
  83      /**
  84       * Loads image from $this->file into new GD Resource.
  85       *
  86       * @since 3.5.0
  87       *
  88       * @return true|WP_Error True if loaded successfully; WP_Error on failure.
  89       */
  90  	public function load() {
  91          if ( $this->image ) {
  92              return true;
  93          }
  94  
  95          if ( ! is_file( $this->file ) && ! preg_match( '|^https?://|', $this->file ) ) {
  96              return new WP_Error( 'error_loading_image', __( 'File does not exist?' ), $this->file );
  97          }
  98  
  99          // Set artificially high because GD uses uncompressed images in memory.
 100          wp_raise_memory_limit( 'image' );
 101  
 102          $file_contents = @file_get_contents( $this->file );
 103  
 104          if ( ! $file_contents ) {
 105              return new WP_Error( 'error_loading_image', __( 'File does not exist?' ), $this->file );
 106          }
 107  
 108          // Handle WebP and AVIF mime types explicitly, falling back to imagecreatefromstring.
 109          if (
 110              function_exists( 'imagecreatefromwebp' ) && ( 'image/webp' === wp_get_image_mime( $this->file ) )
 111          ) {
 112              $this->image = @imagecreatefromwebp( $this->file );
 113          } elseif (
 114              function_exists( 'imagecreatefromavif' ) && ( 'image/avif' === wp_get_image_mime( $this->file ) )
 115          ) {
 116              $this->image = @imagecreatefromavif( $this->file );
 117          } else {
 118              $this->image = @imagecreatefromstring( $file_contents );
 119          }
 120  
 121          if ( ! is_gd_image( $this->image ) ) {
 122              return new WP_Error( 'invalid_image', __( 'File is not an image.' ), $this->file );
 123          }
 124  
 125          $size = wp_getimagesize( $this->file );
 126  
 127          if ( ! $size ) {
 128              return new WP_Error( 'invalid_image', __( 'Could not read image size.' ), $this->file );
 129          }
 130  
 131          if ( function_exists( 'imagealphablending' ) && function_exists( 'imagesavealpha' ) ) {
 132              imagealphablending( $this->image, false );
 133              imagesavealpha( $this->image, true );
 134          }
 135  
 136          $this->update_size( $size[0], $size[1] );
 137          $this->mime_type = $size['mime'];
 138  
 139          return $this->set_quality();
 140      }
 141  
 142      /**
 143       * Sets or updates current image size.
 144       *
 145       * @since 3.5.0
 146       *
 147       * @param int|null $width  Image width.
 148       * @param int|null $height Image height.
 149       * @return true
 150       */
 151  	protected function update_size( $width = null, $height = null ) {
 152          if ( ! $width ) {
 153              $width = imagesx( $this->image );
 154          }
 155  
 156          if ( ! $height ) {
 157              $height = imagesy( $this->image );
 158          }
 159  
 160          return parent::update_size( $width, $height );
 161      }
 162  
 163      /**
 164       * Resizes current image.
 165       *
 166       * Wraps `::_resize()` which returns a GD resource or GdImage instance.
 167       *
 168       * At minimum, either a height or width must be provided. If one of the two is set
 169       * to null, the resize will maintain aspect ratio according to the provided dimension.
 170       *
 171       * @since 3.5.0
 172       *
 173       * @param int|null   $max_w Image width.
 174       * @param int|null   $max_h Image height.
 175       * @param bool|array $crop  {
 176       *     Optional. Image cropping behavior. If false, the image will be scaled (default).
 177       *     If true, image will be cropped to the specified dimensions using center positions.
 178       *     If an array, the image will be cropped using the array to specify the crop location:
 179       *
 180       *     @type string $0 The x crop position. Accepts 'left', 'center', or 'right'.
 181       *     @type string $1 The y crop position. Accepts 'top', 'center', or 'bottom'.
 182       * }
 183       * @return true|WP_Error
 184       */
 185  	public function resize( $max_w, $max_h, $crop = false ) {
 186          if ( ( $this->size['width'] === $max_w ) && ( $this->size['height'] === $max_h ) ) {
 187              return true;
 188          }
 189  
 190          $resized = $this->_resize( $max_w, $max_h, $crop );
 191  
 192          if ( is_gd_image( $resized ) ) {
 193              if ( PHP_VERSION_ID < 80000 ) { // imagedestroy() has no effect as of PHP 8.0.
 194                  imagedestroy( $this->image );
 195              }
 196  
 197              $this->image = $resized;
 198  
 199              return true;
 200  
 201          } elseif ( is_wp_error( $resized ) ) {
 202              return $resized;
 203          }
 204  
 205          return new WP_Error( 'image_resize_error', __( 'Image resize failed.' ), $this->file );
 206      }
 207  
 208      /**
 209       * @param int        $max_w
 210       * @param int        $max_h
 211       * @param bool|array $crop  {
 212       *     Optional. Image cropping behavior. If false, the image will be scaled (default).
 213       *     If true, image will be cropped to the specified dimensions using center positions.
 214       *     If an array, the image will be cropped using the array to specify the crop location:
 215       *
 216       *     @type string $0 The x crop position. Accepts 'left', 'center', or 'right'.
 217       *     @type string $1 The y crop position. Accepts 'top', 'center', or 'bottom'.
 218       * }
 219       * @return resource|GdImage|WP_Error
 220       */
 221  	protected function _resize( $max_w, $max_h, $crop = false ) {
 222          $dims = image_resize_dimensions( $this->size['width'], $this->size['height'], $max_w, $max_h, $crop );
 223  
 224          if ( ! $dims ) {
 225              return new WP_Error( 'error_getting_dimensions', __( 'Could not calculate resized image dimensions' ), $this->file );
 226          }
 227  
 228          list( $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h ) = $dims;
 229  
 230          $this->set_quality(
 231              null,
 232              array(
 233                  'width'  => $dst_w,
 234                  'height' => $dst_h,
 235              )
 236          );
 237  
 238          $resized = wp_imagecreatetruecolor( $dst_w, $dst_h );
 239          imagecopyresampled( $resized, $this->image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h );
 240  
 241          if ( is_gd_image( $resized ) ) {
 242              $this->update_size( $dst_w, $dst_h );
 243              return $resized;
 244          }
 245  
 246          return new WP_Error( 'image_resize_error', __( 'Image resize failed.' ), $this->file );
 247      }
 248  
 249      /**
 250       * Create multiple smaller images from a single source.
 251       *
 252       * Attempts to create all sub-sizes and returns the meta data at the end. This
 253       * may result in the server running out of resources. When it fails there may be few
 254       * "orphaned" images left over as the meta data is never returned and saved.
 255       *
 256       * As of 5.3.0 the preferred way to do this is with `make_subsize()`. It creates
 257       * the new images one at a time and allows for the meta data to be saved after
 258       * each new image is created.
 259       *
 260       * @since 3.5.0
 261       *
 262       * @param array $sizes {
 263       *     An array of image size data arrays.
 264       *
 265       *     Either a height or width must be provided.
 266       *     If one of the two is set to null, the resize will
 267       *     maintain aspect ratio according to the source image.
 268       *
 269       *     @type array ...$0 {
 270       *         Array of height, width values, and whether to crop.
 271       *
 272       *         @type int        $width  Image width. Optional if `$height` is specified.
 273       *         @type int        $height Image height. Optional if `$width` is specified.
 274       *         @type bool|array $crop   Optional. Whether to crop the image. Default false.
 275       *     }
 276       * }
 277       * @return array An array of resized images' metadata by size.
 278       */
 279  	public function multi_resize( $sizes ) {
 280          $metadata = array();
 281  
 282          foreach ( $sizes as $size => $size_data ) {
 283              $meta = $this->make_subsize( $size_data );
 284  
 285              if ( ! is_wp_error( $meta ) ) {
 286                  $metadata[ $size ] = $meta;
 287              }
 288          }
 289  
 290          return $metadata;
 291      }
 292  
 293      /**
 294       * Create an image sub-size and return the image meta data value for it.
 295       *
 296       * @since 5.3.0
 297       *
 298       * @param array $size_data {
 299       *     Array of size data.
 300       *
 301       *     @type int        $width  The maximum width in pixels.
 302       *     @type int        $height The maximum height in pixels.
 303       *     @type bool|array $crop   Whether to crop the image to exact dimensions.
 304       * }
 305       * @return array|WP_Error The image data array for inclusion in the `sizes` array in the image meta,
 306       *                        WP_Error object on error.
 307       */
 308  	public function make_subsize( $size_data ) {
 309          if ( ! isset( $size_data['width'] ) && ! isset( $size_data['height'] ) ) {
 310              return new WP_Error( 'image_subsize_create_error', __( 'Cannot resize the image. Both width and height are not set.' ) );
 311          }
 312  
 313          $orig_size = $this->size;
 314  
 315          $size_data['width']  ??= null;
 316          $size_data['height'] ??= null;
 317          $size_data['crop']   ??= false;
 318  
 319          $resized = $this->_resize( $size_data['width'], $size_data['height'], $size_data['crop'] );
 320  
 321          if ( is_wp_error( $resized ) ) {
 322              $saved = $resized;
 323          } else {
 324              $saved = $this->_save( $resized );
 325  
 326              if ( PHP_VERSION_ID < 80000 ) { // imagedestroy() has no effect as of PHP 8.0.
 327                  imagedestroy( $resized );
 328              }
 329          }
 330  
 331          $this->size = $orig_size;
 332  
 333          if ( ! is_wp_error( $saved ) ) {
 334              unset( $saved['path'] );
 335          }
 336  
 337          return $saved;
 338      }
 339  
 340      /**
 341       * Crops Image.
 342       *
 343       * @since 3.5.0
 344       *
 345       * @param int  $src_x   The start x position to crop from.
 346       * @param int  $src_y   The start y position to crop from.
 347       * @param int  $src_w   The width to crop.
 348       * @param int  $src_h   The height to crop.
 349       * @param int  $dst_w   Optional. The destination width.
 350       * @param int  $dst_h   Optional. The destination height.
 351       * @param bool $src_abs Optional. If the source crop points are absolute.
 352       * @return true|WP_Error
 353       */
 354  	public function crop( $src_x, $src_y, $src_w, $src_h, $dst_w = null, $dst_h = null, $src_abs = false ) {
 355          /*
 356           * If destination width/height isn't specified,
 357           * use same as width/height from source.
 358           */
 359          if ( ! $dst_w ) {
 360              $dst_w = $src_w;
 361          }
 362          if ( ! $dst_h ) {
 363              $dst_h = $src_h;
 364          }
 365  
 366          foreach ( array( $src_w, $src_h, $dst_w, $dst_h ) as $value ) {
 367              if ( ! is_numeric( $value ) || (int) $value <= 0 ) {
 368                  return new WP_Error( 'image_crop_error', __( 'Image crop failed.' ), $this->file );
 369              }
 370          }
 371  
 372          $dst = wp_imagecreatetruecolor( (int) $dst_w, (int) $dst_h );
 373  
 374          if ( $src_abs ) {
 375              $src_w -= $src_x;
 376              $src_h -= $src_y;
 377          }
 378  
 379          if ( function_exists( 'imageantialias' ) ) {
 380              imageantialias( $dst, true );
 381          }
 382  
 383          imagecopyresampled( $dst, $this->image, 0, 0, (int) $src_x, (int) $src_y, (int) $dst_w, (int) $dst_h, (int) $src_w, (int) $src_h );
 384  
 385          if ( is_gd_image( $dst ) ) {
 386              if ( PHP_VERSION_ID < 80000 ) { // imagedestroy() has no effect as of PHP 8.0.
 387                  imagedestroy( $this->image );
 388              }
 389  
 390              $this->image = $dst;
 391              $this->update_size();
 392  
 393              return true;
 394          }
 395  
 396          return new WP_Error( 'image_crop_error', __( 'Image crop failed.' ), $this->file );
 397      }
 398  
 399      /**
 400       * Rotates current image counter-clockwise by $angle.
 401       * Ported from image-edit.php
 402       *
 403       * @since 3.5.0
 404       *
 405       * @param float $angle
 406       * @return true|WP_Error
 407       */
 408  	public function rotate( $angle ) {
 409          if ( function_exists( 'imagerotate' ) ) {
 410              $transparency = imagecolorallocatealpha( $this->image, 255, 255, 255, 127 );
 411              $rotated      = imagerotate( $this->image, $angle, $transparency );
 412  
 413              if ( is_gd_image( $rotated ) ) {
 414                  imagealphablending( $rotated, true );
 415                  imagesavealpha( $rotated, true );
 416  
 417                  if ( PHP_VERSION_ID < 80000 ) { // imagedestroy() has no effect as of PHP 8.0.
 418                      imagedestroy( $this->image );
 419                  }
 420  
 421                  $this->image = $rotated;
 422                  $this->update_size();
 423  
 424                  return true;
 425              }
 426          }
 427  
 428          return new WP_Error( 'image_rotate_error', __( 'Image rotate failed.' ), $this->file );
 429      }
 430  
 431      /**
 432       * Flips current image.
 433       *
 434       * @since 3.5.0
 435       * @since 7.2.0 Switched to using imageflip() instead of imagecopyresampled() with negative dimensions.
 436       *
 437       * @param bool $horz Flip along Horizontal Axis.
 438       * @param bool $vert Flip along Vertical Axis.
 439       * @return true|WP_Error
 440       */
 441  	public function flip( $horz, $vert ) {
 442          if ( ! is_gd_image( $this->image ) ) {
 443              return new WP_Error( 'image_flip_error', __( 'Image flip failed.' ), $this->file );
 444          }
 445  
 446          /*
 447           * imageflip() works in place and keeps palette images as palette images.
 448           * The previous implementation always copied into a new truecolor image,
 449           * and saving or streaming as WebP relies on that, since imagewebp()
 450           * rejects palette images. Convert first to keep that behavior.
 451           */
 452          if ( ! imageistruecolor( $this->image ) && ! imagepalettetotruecolor( $this->image ) ) {
 453              return new WP_Error( 'image_flip_error', __( 'Image flip failed.' ), $this->file );
 454          }
 455  
 456          /*
 457           * imageflip() also keeps the current alpha settings, which rotate() leaves
 458           * with blending enabled. Reset them to what the previous implementation
 459           * always produced, including when no axis is flipped.
 460           */
 461          imagealphablending( $this->image, false );
 462          imagesavealpha( $this->image, true );
 463  
 464          /*
 465           * imageflip() changes the image in place, so the image keeps its current resolution and interlace setting.
 466           * rotate(), crop() and resize() copy into a new image, which resets them to GD's defaults: 96 DPI and no
 467           * interlacing. Reset them here too, so a flip gives the same result as the other edits.
 468           *
 469           * @link https://core.trac.wordpress.org/ticket/66113
 470           */
 471          imageresolution( $this->image, 96, 96 );
 472          imageinterlace( $this->image, 0 );
 473  
 474          if ( ! $horz && ! $vert ) {
 475              return true;
 476          }
 477  
 478          if ( $horz && $vert ) {
 479              $mode = IMG_FLIP_BOTH;
 480          } elseif ( $horz ) {
 481              $mode = IMG_FLIP_VERTICAL;
 482          } else {
 483              $mode = IMG_FLIP_HORIZONTAL;
 484          }
 485  
 486          if ( imageflip( $this->image, $mode ) ) {
 487              return true;
 488          }
 489  
 490          return new WP_Error( 'image_flip_error', __( 'Image flip failed.' ), $this->file );
 491      }
 492  
 493      /**
 494       * Saves current in-memory image to file.
 495       *
 496       * @since 3.5.0
 497       * @since 5.9.0 Renamed `$filename` to `$destfilename` to match parent class
 498       *              for PHP 8 named parameter support.
 499       * @since 6.0.0 The `$filesize` value was added to the returned array.
 500       *
 501       * @param string|null $destfilename Optional. Destination filename. Default null.
 502       * @param string|null $mime_type    Optional. The mime-type. Default null.
 503       * @return array|WP_Error {
 504       *     Array on success or WP_Error if the file failed to save.
 505       *
 506       *     @type string $path      Path to the image file.
 507       *     @type string $file      Name of the image file.
 508       *     @type int    $width     Image width.
 509       *     @type int    $height    Image height.
 510       *     @type string $mime-type The mime type of the image.
 511       *     @type int    $filesize  File size of the image.
 512       * }
 513       */
 514  	public function save( $destfilename = null, $mime_type = null ) {
 515          $saved = $this->_save( $this->image, $destfilename, $mime_type );
 516  
 517          if ( ! is_wp_error( $saved ) ) {
 518              $this->file      = $saved['path'];
 519              $this->mime_type = $saved['mime-type'];
 520          }
 521  
 522          return $saved;
 523      }
 524  
 525      /**
 526       * @since 3.5.0
 527       * @since 6.0.0 The `$filesize` value was added to the returned array.
 528       *
 529       * @param resource|GdImage $image
 530       * @param string|null      $filename
 531       * @param string|null      $mime_type
 532       * @return array|WP_Error {
 533       *     Array on success or WP_Error if the file failed to save.
 534       *
 535       *     @type string $path      Path to the image file.
 536       *     @type string $file      Name of the image file.
 537       *     @type int    $width     Image width.
 538       *     @type int    $height    Image height.
 539       *     @type string $mime-type The mime type of the image.
 540       *     @type int    $filesize  File size of the image.
 541       * }
 542       */
 543  	protected function _save( $image, $filename = null, $mime_type = null ) {
 544          list( $filename, $extension, $mime_type ) = $this->get_output_format( $filename, $mime_type );
 545  
 546          if ( ! $filename ) {
 547              $filename = $this->generate_filename( null, null, $extension );
 548          }
 549  
 550          if ( function_exists( 'imageinterlace' ) ) {
 551              /**
 552               * Filters whether to output progressive images (if available).
 553               *
 554               * @since 6.5.0
 555               *
 556               * @param bool   $interlace Whether to use progressive images for output if available. Default false.
 557               * @param string $mime_type The mime type being saved.
 558               */
 559              imageinterlace( $image, apply_filters( 'image_save_progressive', false, $mime_type ) );
 560          }
 561  
 562          if ( 'image/gif' === $mime_type ) {
 563              if ( ! $this->make_image( $filename, 'imagegif', array( $image, $filename ) ) ) {
 564                  return new WP_Error( 'image_save_error', __( 'Image Editor Save Failed' ) );
 565              }
 566          } elseif ( 'image/png' === $mime_type ) {
 567              // Convert from full colors to index colors, like original PNG.
 568              if ( function_exists( 'imageistruecolor' ) && ! imageistruecolor( $image ) ) {
 569                  imagetruecolortopalette( $image, false, imagecolorstotal( $image ) );
 570              }
 571  
 572              if ( ! $this->make_image( $filename, 'imagepng', array( $image, $filename ) ) ) {
 573                  return new WP_Error( 'image_save_error', __( 'Image Editor Save Failed' ) );
 574              }
 575          } elseif ( 'image/jpeg' === $mime_type ) {
 576              if ( ! $this->make_image( $filename, 'imagejpeg', array( $image, $filename, $this->get_quality() ) ) ) {
 577                  return new WP_Error( 'image_save_error', __( 'Image Editor Save Failed' ) );
 578              }
 579          } elseif ( 'image/webp' === $mime_type ) {
 580              if ( ! function_exists( 'imagewebp' )
 581                  || ! $this->make_image( $filename, 'imagewebp', array( $image, $filename, $this->get_quality() ) )
 582              ) {
 583                  return new WP_Error( 'image_save_error', __( 'Image Editor Save Failed' ) );
 584              }
 585          } elseif ( 'image/avif' === $mime_type ) {
 586              if ( ! function_exists( 'imageavif' )
 587                  || ! $this->make_image( $filename, 'imageavif', array( $image, $filename, $this->get_quality() ) )
 588              ) {
 589                  return new WP_Error( 'image_save_error', __( 'Image Editor Save Failed' ) );
 590              }
 591          } else {
 592              return new WP_Error( 'image_save_error', __( 'Image Editor Save Failed' ) );
 593          }
 594  
 595          // Set correct file permissions.
 596          $stat  = stat( dirname( $filename ) );
 597          $perms = $stat['mode'] & 0000666; // Same permissions as parent folder, strip off the executable bits.
 598          chmod( $filename, $perms );
 599  
 600          return array(
 601              'path'      => $filename,
 602              /**
 603               * Filters the name of the saved image file.
 604               *
 605               * @since 2.6.0
 606               *
 607               * @param string $filename Name of the file.
 608               */
 609              'file'      => wp_basename( apply_filters( 'image_make_intermediate_size', $filename ) ),
 610              'width'     => $this->size['width'],
 611              'height'    => $this->size['height'],
 612              'mime-type' => $mime_type,
 613              'filesize'  => wp_filesize( $filename ),
 614          );
 615      }
 616  
 617      /**
 618       * Sets Image Compression quality on a 1-100% scale. Handles WebP lossless images.
 619       *
 620       * @since 6.7.0
 621       * @since 6.8.0 The `$dims` parameter was added.
 622       *
 623       * @param int   $quality Compression Quality. Range: [1,100]
 624       * @param array $dims    Optional. Image dimensions array with 'width' and 'height' keys.
 625       * @return true|WP_Error True if set successfully; WP_Error on failure.
 626       */
 627  	public function set_quality( $quality = null, $dims = array() ) {
 628          $quality_result = parent::set_quality( $quality, $dims );
 629          if ( is_wp_error( $quality_result ) ) {
 630              return $quality_result;
 631          } else {
 632              $quality = $this->get_quality();
 633          }
 634  
 635          // Handle setting the quality for WebP lossless images, see https://php.watch/versions/8.1/gd-webp-lossless.
 636          try {
 637              if ( 'image/webp' === $this->mime_type && defined( 'IMG_WEBP_LOSSLESS' ) ) {
 638                  $webp_info = wp_get_webp_info( $this->file );
 639                  if ( ! empty( $webp_info['type'] ) && 'lossless' === $webp_info['type'] ) {
 640                      $quality = IMG_WEBP_LOSSLESS;
 641                      parent::set_quality( $quality, $dims );
 642                  }
 643              }
 644          } catch ( Exception $e ) {
 645              return new WP_Error( 'image_quality_error', $e->getMessage() );
 646          }
 647          $this->quality = $quality;
 648          return true;
 649      }
 650  
 651      /**
 652       * Returns stream of current image.
 653       *
 654       * @since 3.5.0
 655       *
 656       * @param string $mime_type The mime type of the image.
 657       * @return bool True on success, false on failure.
 658       */
 659  	public function stream( $mime_type = null ) {
 660          list( $filename, $extension, $mime_type ) = $this->get_output_format( null, $mime_type );
 661  
 662          switch ( $mime_type ) {
 663              case 'image/png':
 664                  header( 'Content-Type: image/png' );
 665                  return imagepng( $this->image );
 666              case 'image/gif':
 667                  header( 'Content-Type: image/gif' );
 668                  return imagegif( $this->image );
 669              case 'image/webp':
 670                  if ( function_exists( 'imagewebp' ) ) {
 671                      header( 'Content-Type: image/webp' );
 672                      return imagewebp( $this->image, null, $this->get_quality() );
 673                  } else {
 674                      // Fall back to JPEG.
 675                      header( 'Content-Type: image/jpeg' );
 676                      return imagejpeg( $this->image, null, $this->get_quality() );
 677                  }
 678              case 'image/avif':
 679                  if ( function_exists( 'imageavif' ) ) {
 680                      header( 'Content-Type: image/avif' );
 681                      return imageavif( $this->image, null, $this->get_quality() );
 682                  }
 683                  // Fall back to JPEG.
 684              default:
 685                  header( 'Content-Type: image/jpeg' );
 686                  return imagejpeg( $this->image, null, $this->get_quality() );
 687          }
 688      }
 689  
 690      /**
 691       * Either calls editor's save function or handles file as a stream.
 692       *
 693       * @since 3.5.0
 694       *
 695       * @param string   $filename
 696       * @param callable $callback
 697       * @param array    $arguments
 698       * @return bool
 699       */
 700  	protected function make_image( $filename, $callback, $arguments ) {
 701          if ( wp_is_stream( $filename ) ) {
 702              $arguments[1] = null;
 703          }
 704  
 705          return parent::make_image( $filename, $callback, $arguments );
 706      }
 707  }


Generated : Wed Nov 18 08:20:02 2026 Cross-referenced by PHPXref