| [ Index ] |
PHP Cross Reference of WordPress Trunk (Updated Daily) |
[Summary view] [Print] [Text view]
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 * 436 * @param bool $horz Flip along Horizontal Axis. 437 * @param bool $vert Flip along Vertical Axis. 438 * @return true|WP_Error 439 */ 440 public function flip( $horz, $vert ) { 441 $w = $this->size['width']; 442 $h = $this->size['height']; 443 $dst = wp_imagecreatetruecolor( $w, $h ); 444 445 if ( is_gd_image( $dst ) ) { 446 $sx = $vert ? ( $w - 1 ) : 0; 447 $sy = $horz ? ( $h - 1 ) : 0; 448 $sw = $vert ? -$w : $w; 449 $sh = $horz ? -$h : $h; 450 451 if ( imagecopyresampled( $dst, $this->image, 0, 0, $sx, $sy, $w, $h, $sw, $sh ) ) { 452 if ( PHP_VERSION_ID < 80000 ) { // imagedestroy() has no effect as of PHP 8.0. 453 imagedestroy( $this->image ); 454 } 455 456 $this->image = $dst; 457 458 return true; 459 } 460 } 461 462 return new WP_Error( 'image_flip_error', __( 'Image flip failed.' ), $this->file ); 463 } 464 465 /** 466 * Saves current in-memory image to file. 467 * 468 * @since 3.5.0 469 * @since 5.9.0 Renamed `$filename` to `$destfilename` to match parent class 470 * for PHP 8 named parameter support. 471 * @since 6.0.0 The `$filesize` value was added to the returned array. 472 * 473 * @param string|null $destfilename Optional. Destination filename. Default null. 474 * @param string|null $mime_type Optional. The mime-type. Default null. 475 * @return array|WP_Error { 476 * Array on success or WP_Error if the file failed to save. 477 * 478 * @type string $path Path to the image file. 479 * @type string $file Name of the image file. 480 * @type int $width Image width. 481 * @type int $height Image height. 482 * @type string $mime-type The mime type of the image. 483 * @type int $filesize File size of the image. 484 * } 485 */ 486 public function save( $destfilename = null, $mime_type = null ) { 487 $saved = $this->_save( $this->image, $destfilename, $mime_type ); 488 489 if ( ! is_wp_error( $saved ) ) { 490 $this->file = $saved['path']; 491 $this->mime_type = $saved['mime-type']; 492 } 493 494 return $saved; 495 } 496 497 /** 498 * @since 3.5.0 499 * @since 6.0.0 The `$filesize` value was added to the returned array. 500 * 501 * @param resource|GdImage $image 502 * @param string|null $filename 503 * @param string|null $mime_type 504 * @return array|WP_Error { 505 * Array on success or WP_Error if the file failed to save. 506 * 507 * @type string $path Path to the image file. 508 * @type string $file Name of the image file. 509 * @type int $width Image width. 510 * @type int $height Image height. 511 * @type string $mime-type The mime type of the image. 512 * @type int $filesize File size of the image. 513 * } 514 */ 515 protected function _save( $image, $filename = null, $mime_type = null ) { 516 list( $filename, $extension, $mime_type ) = $this->get_output_format( $filename, $mime_type ); 517 518 if ( ! $filename ) { 519 $filename = $this->generate_filename( null, null, $extension ); 520 } 521 522 if ( function_exists( 'imageinterlace' ) ) { 523 /** 524 * Filters whether to output progressive images (if available). 525 * 526 * @since 6.5.0 527 * 528 * @param bool $interlace Whether to use progressive images for output if available. Default false. 529 * @param string $mime_type The mime type being saved. 530 */ 531 imageinterlace( $image, apply_filters( 'image_save_progressive', false, $mime_type ) ); 532 } 533 534 if ( 'image/gif' === $mime_type ) { 535 if ( ! $this->make_image( $filename, 'imagegif', array( $image, $filename ) ) ) { 536 return new WP_Error( 'image_save_error', __( 'Image Editor Save Failed' ) ); 537 } 538 } elseif ( 'image/png' === $mime_type ) { 539 // Convert from full colors to index colors, like original PNG. 540 if ( function_exists( 'imageistruecolor' ) && ! imageistruecolor( $image ) ) { 541 imagetruecolortopalette( $image, false, imagecolorstotal( $image ) ); 542 } 543 544 if ( ! $this->make_image( $filename, 'imagepng', array( $image, $filename ) ) ) { 545 return new WP_Error( 'image_save_error', __( 'Image Editor Save Failed' ) ); 546 } 547 } elseif ( 'image/jpeg' === $mime_type ) { 548 if ( ! $this->make_image( $filename, 'imagejpeg', array( $image, $filename, $this->get_quality() ) ) ) { 549 return new WP_Error( 'image_save_error', __( 'Image Editor Save Failed' ) ); 550 } 551 } elseif ( 'image/webp' === $mime_type ) { 552 if ( ! function_exists( 'imagewebp' ) 553 || ! $this->make_image( $filename, 'imagewebp', array( $image, $filename, $this->get_quality() ) ) 554 ) { 555 return new WP_Error( 'image_save_error', __( 'Image Editor Save Failed' ) ); 556 } 557 } elseif ( 'image/avif' === $mime_type ) { 558 if ( ! function_exists( 'imageavif' ) 559 || ! $this->make_image( $filename, 'imageavif', array( $image, $filename, $this->get_quality() ) ) 560 ) { 561 return new WP_Error( 'image_save_error', __( 'Image Editor Save Failed' ) ); 562 } 563 } else { 564 return new WP_Error( 'image_save_error', __( 'Image Editor Save Failed' ) ); 565 } 566 567 // Set correct file permissions. 568 $stat = stat( dirname( $filename ) ); 569 $perms = $stat['mode'] & 0000666; // Same permissions as parent folder, strip off the executable bits. 570 chmod( $filename, $perms ); 571 572 return array( 573 'path' => $filename, 574 /** 575 * Filters the name of the saved image file. 576 * 577 * @since 2.6.0 578 * 579 * @param string $filename Name of the file. 580 */ 581 'file' => wp_basename( apply_filters( 'image_make_intermediate_size', $filename ) ), 582 'width' => $this->size['width'], 583 'height' => $this->size['height'], 584 'mime-type' => $mime_type, 585 'filesize' => wp_filesize( $filename ), 586 ); 587 } 588 589 /** 590 * Sets Image Compression quality on a 1-100% scale. Handles WebP lossless images. 591 * 592 * @since 6.7.0 593 * @since 6.8.0 The `$dims` parameter was added. 594 * 595 * @param int $quality Compression Quality. Range: [1,100] 596 * @param array $dims Optional. Image dimensions array with 'width' and 'height' keys. 597 * @return true|WP_Error True if set successfully; WP_Error on failure. 598 */ 599 public function set_quality( $quality = null, $dims = array() ) { 600 $quality_result = parent::set_quality( $quality, $dims ); 601 if ( is_wp_error( $quality_result ) ) { 602 return $quality_result; 603 } else { 604 $quality = $this->get_quality(); 605 } 606 607 // Handle setting the quality for WebP lossless images, see https://php.watch/versions/8.1/gd-webp-lossless. 608 try { 609 if ( 'image/webp' === $this->mime_type && defined( 'IMG_WEBP_LOSSLESS' ) ) { 610 $webp_info = wp_get_webp_info( $this->file ); 611 if ( ! empty( $webp_info['type'] ) && 'lossless' === $webp_info['type'] ) { 612 $quality = IMG_WEBP_LOSSLESS; 613 parent::set_quality( $quality, $dims ); 614 } 615 } 616 } catch ( Exception $e ) { 617 return new WP_Error( 'image_quality_error', $e->getMessage() ); 618 } 619 $this->quality = $quality; 620 return true; 621 } 622 623 /** 624 * Returns stream of current image. 625 * 626 * @since 3.5.0 627 * 628 * @param string $mime_type The mime type of the image. 629 * @return bool True on success, false on failure. 630 */ 631 public function stream( $mime_type = null ) { 632 list( $filename, $extension, $mime_type ) = $this->get_output_format( null, $mime_type ); 633 634 switch ( $mime_type ) { 635 case 'image/png': 636 header( 'Content-Type: image/png' ); 637 return imagepng( $this->image ); 638 case 'image/gif': 639 header( 'Content-Type: image/gif' ); 640 return imagegif( $this->image ); 641 case 'image/webp': 642 if ( function_exists( 'imagewebp' ) ) { 643 header( 'Content-Type: image/webp' ); 644 return imagewebp( $this->image, null, $this->get_quality() ); 645 } else { 646 // Fall back to JPEG. 647 header( 'Content-Type: image/jpeg' ); 648 return imagejpeg( $this->image, null, $this->get_quality() ); 649 } 650 case 'image/avif': 651 if ( function_exists( 'imageavif' ) ) { 652 header( 'Content-Type: image/avif' ); 653 return imageavif( $this->image, null, $this->get_quality() ); 654 } 655 // Fall back to JPEG. 656 default: 657 header( 'Content-Type: image/jpeg' ); 658 return imagejpeg( $this->image, null, $this->get_quality() ); 659 } 660 } 661 662 /** 663 * Either calls editor's save function or handles file as a stream. 664 * 665 * @since 3.5.0 666 * 667 * @param string $filename 668 * @param callable $callback 669 * @param array $arguments 670 * @return bool 671 */ 672 protected function make_image( $filename, $callback, $arguments ) { 673 if ( wp_is_stream( $filename ) ) { 674 $arguments[1] = null; 675 } 676 677 return parent::make_image( $filename, $callback, $arguments ); 678 } 679 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
| Generated : Thu Sep 17 08:20:31 2026 | Cross-referenced by PHPXref |