[ Index ] |
PHP Cross Reference of WordPress Trunk (Updated Daily) |
[Summary view] [Print] [Text view]
1 <?php 2 /** 3 * WordPress Imagick Image Editor 4 * 5 * @package WordPress 6 * @subpackage Image_Editor 7 */ 8 9 /** 10 * WordPress Image Editor Class for Image Manipulation through Imagick PHP Module 11 * 12 * @since 3.5.0 13 * 14 * @see WP_Image_Editor 15 */ 16 class WP_Image_Editor_Imagick extends WP_Image_Editor { 17 /** 18 * Imagick object. 19 * 20 * @var Imagick 21 */ 22 protected $image; 23 24 public function __destruct() { 25 if ( $this->image instanceof Imagick ) { 26 // We don't need the original in memory anymore. 27 $this->image->clear(); 28 $this->image->destroy(); 29 } 30 } 31 32 /** 33 * Checks to see if current environment supports Imagick. 34 * 35 * We require Imagick 2.2.0 or greater, based on whether the queryFormats() 36 * method can be called statically. 37 * 38 * @since 3.5.0 39 * 40 * @param array $args 41 * @return bool 42 */ 43 public static function test( $args = array() ) { 44 45 // First, test Imagick's extension and classes. 46 if ( ! extension_loaded( 'imagick' ) || ! class_exists( 'Imagick', false ) || ! class_exists( 'ImagickPixel', false ) ) { 47 return false; 48 } 49 50 if ( version_compare( phpversion( 'imagick' ), '2.2.0', '<' ) ) { 51 return false; 52 } 53 54 $required_methods = array( 55 'clear', 56 'destroy', 57 'valid', 58 'getimage', 59 'writeimage', 60 'getimageblob', 61 'getimagegeometry', 62 'getimageformat', 63 'setimageformat', 64 'setimagecompression', 65 'setimagecompressionquality', 66 'setimagepage', 67 'setoption', 68 'scaleimage', 69 'cropimage', 70 'rotateimage', 71 'flipimage', 72 'flopimage', 73 'readimage', 74 'readimageblob', 75 ); 76 77 // Now, test for deep requirements within Imagick. 78 if ( ! defined( 'imagick::COMPRESSION_JPEG' ) ) { 79 return false; 80 } 81 82 $class_methods = array_map( 'strtolower', get_class_methods( 'Imagick' ) ); 83 if ( array_diff( $required_methods, $class_methods ) ) { 84 return false; 85 } 86 87 return true; 88 } 89 90 /** 91 * Checks to see if editor supports the mime-type specified. 92 * 93 * @since 3.5.0 94 * 95 * @param string $mime_type 96 * @return bool 97 */ 98 public static function supports_mime_type( $mime_type ) { 99 $imagick_extension = strtoupper( self::get_extension( $mime_type ) ); 100 101 if ( ! $imagick_extension ) { 102 return false; 103 } 104 105 /* 106 * setIteratorIndex is optional unless mime is an animated format. 107 * Here, we just say no if you are missing it and aren't loading a jpeg. 108 */ 109 if ( ! method_exists( 'Imagick', 'setIteratorIndex' ) && 'image/jpeg' !== $mime_type ) { 110 return false; 111 } 112 113 try { 114 // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged 115 return ( (bool) @Imagick::queryFormats( $imagick_extension ) ); 116 } catch ( Exception $e ) { 117 return false; 118 } 119 } 120 121 /** 122 * Loads image from $this->file into new Imagick Object. 123 * 124 * @since 3.5.0 125 * 126 * @return true|WP_Error True if loaded; WP_Error on failure. 127 */ 128 public function load() { 129 if ( $this->image instanceof Imagick ) { 130 return true; 131 } 132 133 if ( ! is_file( $this->file ) && ! wp_is_stream( $this->file ) ) { 134 return new WP_Error( 'error_loading_image', __( 'File does not exist?' ), $this->file ); 135 } 136 137 /* 138 * Even though Imagick uses less PHP memory than GD, set higher limit 139 * for users that have low PHP.ini limits. 140 */ 141 wp_raise_memory_limit( 'image' ); 142 143 try { 144 $this->image = new Imagick(); 145 $file_extension = strtolower( pathinfo( $this->file, PATHINFO_EXTENSION ) ); 146 147 if ( 'pdf' === $file_extension ) { 148 $pdf_loaded = $this->pdf_load_source(); 149 150 if ( is_wp_error( $pdf_loaded ) ) { 151 return $pdf_loaded; 152 } 153 } else { 154 if ( wp_is_stream( $this->file ) ) { 155 // Due to reports of issues with streams with `Imagick::readImageFile()`, uses `Imagick::readImageBlob()` instead. 156 $this->image->readImageBlob( file_get_contents( $this->file ), $this->file ); 157 } else { 158 $this->image->readImage( $this->file ); 159 } 160 } 161 162 if ( ! $this->image->valid() ) { 163 return new WP_Error( 'invalid_image', __( 'File is not an image.' ), $this->file ); 164 } 165 166 // Select the first frame to handle animated images properly. 167 if ( is_callable( array( $this->image, 'setIteratorIndex' ) ) ) { 168 $this->image->setIteratorIndex( 0 ); 169 } 170 171 if ( 'pdf' === $file_extension ) { 172 $this->remove_pdf_alpha_channel(); 173 } 174 175 $this->mime_type = $this->get_mime_type( $this->image->getImageFormat() ); 176 } catch ( Exception $e ) { 177 return new WP_Error( 'invalid_image', $e->getMessage(), $this->file ); 178 } 179 180 $updated_size = $this->update_size(); 181 182 if ( is_wp_error( $updated_size ) ) { 183 return $updated_size; 184 } 185 186 return $this->set_quality(); 187 } 188 189 /** 190 * Sets Image Compression quality on a 1-100% scale. 191 * 192 * @since 3.5.0 193 * @since 6.8.0 The `$dims` parameter was added. 194 * 195 * @param int $quality Compression Quality. Range: [1,100] 196 * @param array $dims Optional. Image dimensions array with 'width' and 'height' keys. 197 * @return true|WP_Error True if set successfully; WP_Error on failure. 198 */ 199 public function set_quality( $quality = null, $dims = array() ) { 200 $quality_result = parent::set_quality( $quality, $dims ); 201 if ( is_wp_error( $quality_result ) ) { 202 return $quality_result; 203 } else { 204 $quality = $this->get_quality(); 205 } 206 207 try { 208 switch ( $this->mime_type ) { 209 case 'image/jpeg': 210 $this->image->setImageCompressionQuality( $quality ); 211 $this->image->setCompressionQuality( $quality ); 212 $this->image->setImageCompression( imagick::COMPRESSION_JPEG ); 213 break; 214 case 'image/webp': 215 $webp_info = wp_get_webp_info( $this->file ); 216 217 if ( 'lossless' === $webp_info['type'] ) { 218 // Use WebP lossless settings. 219 $this->image->setImageCompressionQuality( 100 ); 220 $this->image->setCompressionQuality( 100 ); 221 $this->image->setOption( 'webp:lossless', 'true' ); 222 parent::set_quality( 100 ); 223 } else { 224 $this->image->setImageCompressionQuality( $quality ); 225 $this->image->setCompressionQuality( $quality ); 226 } 227 break; 228 case 'image/avif': 229 // Set the AVIF encoder to work faster, with minimal impact on image size. 230 $this->image->setOption( 'heic:speed', 7 ); 231 $this->image->setImageCompressionQuality( $quality ); 232 $this->image->setCompressionQuality( $quality ); 233 break; 234 default: 235 $this->image->setImageCompressionQuality( $quality ); 236 $this->image->setCompressionQuality( $quality ); 237 } 238 } catch ( Exception $e ) { 239 return new WP_Error( 'image_quality_error', $e->getMessage() ); 240 } 241 return true; 242 } 243 244 245 /** 246 * Sets or updates current image size. 247 * 248 * @since 3.5.0 249 * 250 * @param int $width 251 * @param int $height 252 * @return true|WP_Error 253 */ 254 protected function update_size( $width = null, $height = null ) { 255 $size = null; 256 if ( ! $width || ! $height ) { 257 try { 258 $size = $this->image->getImageGeometry(); 259 } catch ( Exception $e ) { 260 return new WP_Error( 'invalid_image', __( 'Could not read image size.' ), $this->file ); 261 } 262 } 263 264 if ( ! $width ) { 265 $width = $size['width']; 266 } 267 268 if ( ! $height ) { 269 $height = $size['height']; 270 } 271 272 /* 273 * If we still don't have the image size, fall back to `wp_getimagesize`. This ensures AVIF and HEIC images 274 * are properly sized without affecting previous `getImageGeometry` behavior. 275 */ 276 if ( ( ! $width || ! $height ) && ( 'image/avif' === $this->mime_type || wp_is_heic_image_mime_type( $this->mime_type ) ) ) { 277 $size = wp_getimagesize( $this->file ); 278 $width = $size[0]; 279 $height = $size[1]; 280 } 281 282 return parent::update_size( $width, $height ); 283 } 284 285 /** 286 * Sets Imagick time limit. 287 * 288 * Depending on configuration, Imagick processing may take time. 289 * 290 * Multiple problems exist if PHP times out before ImageMagick completed: 291 * 1. Temporary files aren't cleaned by ImageMagick garbage collection. 292 * 2. No clear error is provided. 293 * 3. The cause of such timeout can be hard to pinpoint. 294 * 295 * This function, which is expected to be run before heavy image routines, resolves 296 * point 1 above by aligning Imagick's timeout with PHP's timeout, assuming it is set. 297 * 298 * However seems it introduces more problems than it fixes, 299 * see https://core.trac.wordpress.org/ticket/58202. 300 * 301 * Note: 302 * - Imagick resource exhaustion does not issue catchable exceptions (yet). 303 * See https://github.com/Imagick/imagick/issues/333. 304 * - The resource limit is not saved/restored. It applies to subsequent 305 * image operations within the time of the HTTP request. 306 * 307 * @since 6.2.0 308 * @since 6.3.0 This method was deprecated. 309 * 310 * @return int|null The new limit on success, null on failure. 311 */ 312 public static function set_imagick_time_limit() { 313 _deprecated_function( __METHOD__, '6.3.0' ); 314 315 if ( ! defined( 'Imagick::RESOURCETYPE_TIME' ) ) { 316 return null; 317 } 318 319 // Returns PHP_FLOAT_MAX if unset. 320 $imagick_timeout = Imagick::getResourceLimit( Imagick::RESOURCETYPE_TIME ); 321 322 // Convert to an integer, keeping in mind that: 0 === (int) PHP_FLOAT_MAX. 323 $imagick_timeout = $imagick_timeout > PHP_INT_MAX ? PHP_INT_MAX : (int) $imagick_timeout; 324 325 $php_timeout = (int) ini_get( 'max_execution_time' ); 326 327 if ( $php_timeout > 1 && $php_timeout < $imagick_timeout ) { 328 $limit = (float) 0.8 * $php_timeout; 329 Imagick::setResourceLimit( Imagick::RESOURCETYPE_TIME, $limit ); 330 331 return $limit; 332 } 333 } 334 335 /** 336 * Resizes current image. 337 * 338 * At minimum, either a height or width must be provided. 339 * If one of the two is set to null, the resize will 340 * maintain aspect ratio according to the provided dimension. 341 * 342 * @since 3.5.0 343 * 344 * @param int|null $max_w Image width. 345 * @param int|null $max_h Image height. 346 * @param bool|array $crop { 347 * Optional. Image cropping behavior. If false, the image will be scaled (default). 348 * If true, image will be cropped to the specified dimensions using center positions. 349 * If an array, the image will be cropped using the array to specify the crop location: 350 * 351 * @type string $0 The x crop position. Accepts 'left', 'center', or 'right'. 352 * @type string $1 The y crop position. Accepts 'top', 'center', or 'bottom'. 353 * } 354 * @return true|WP_Error 355 */ 356 public function resize( $max_w, $max_h, $crop = false ) { 357 if ( ( $this->size['width'] === $max_w ) && ( $this->size['height'] === $max_h ) ) { 358 return true; 359 } 360 361 $dims = image_resize_dimensions( $this->size['width'], $this->size['height'], $max_w, $max_h, $crop ); 362 if ( ! $dims ) { 363 return new WP_Error( 'error_getting_dimensions', __( 'Could not calculate resized image dimensions' ) ); 364 } 365 366 list( $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h ) = $dims; 367 368 if ( $crop ) { 369 return $this->crop( $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h ); 370 } 371 372 $this->set_quality( 373 null, 374 array( 375 'width' => $dst_w, 376 'height' => $dst_h, 377 ) 378 ); 379 380 // Execute the resize. 381 $thumb_result = $this->thumbnail_image( $dst_w, $dst_h ); 382 if ( is_wp_error( $thumb_result ) ) { 383 return $thumb_result; 384 } 385 386 return $this->update_size( $dst_w, $dst_h ); 387 } 388 389 /** 390 * Efficiently resize the current image 391 * 392 * This is a WordPress specific implementation of Imagick::thumbnailImage(), 393 * which resizes an image to given dimensions and removes any associated profiles. 394 * 395 * @since 4.5.0 396 * 397 * @param int $dst_w The destination width. 398 * @param int $dst_h The destination height. 399 * @param string $filter_name Optional. The Imagick filter to use when resizing. Default 'FILTER_TRIANGLE'. 400 * @param bool $strip_meta Optional. Strip all profiles, excluding color profiles, from the image. Default true. 401 * @return void|WP_Error 402 */ 403 protected function thumbnail_image( $dst_w, $dst_h, $filter_name = 'FILTER_TRIANGLE', $strip_meta = true ) { 404 $allowed_filters = array( 405 'FILTER_POINT', 406 'FILTER_BOX', 407 'FILTER_TRIANGLE', 408 'FILTER_HERMITE', 409 'FILTER_HANNING', 410 'FILTER_HAMMING', 411 'FILTER_BLACKMAN', 412 'FILTER_GAUSSIAN', 413 'FILTER_QUADRATIC', 414 'FILTER_CUBIC', 415 'FILTER_CATROM', 416 'FILTER_MITCHELL', 417 'FILTER_LANCZOS', 418 'FILTER_BESSEL', 419 'FILTER_SINC', 420 ); 421 422 /** 423 * Set the filter value if '$filter_name' name is in the allowed list and the related 424 * Imagick constant is defined or fall back to the default filter. 425 */ 426 if ( in_array( $filter_name, $allowed_filters, true ) && defined( 'Imagick::' . $filter_name ) ) { 427 $filter = constant( 'Imagick::' . $filter_name ); 428 } else { 429 $filter = defined( 'Imagick::FILTER_TRIANGLE' ) ? Imagick::FILTER_TRIANGLE : false; 430 } 431 432 /** 433 * Filters whether to strip metadata from images when they're resized. 434 * 435 * This filter only applies when resizing using the Imagick editor since GD 436 * always strips profiles by default. 437 * 438 * @since 4.5.0 439 * 440 * @param bool $strip_meta Whether to strip image metadata during resizing. Default true. 441 */ 442 if ( apply_filters( 'image_strip_meta', $strip_meta ) ) { 443 $this->strip_meta(); // Fail silently if not supported. 444 } 445 446 try { 447 /* 448 * To be more efficient, resample large images to 5x the destination size before resizing 449 * whenever the output size is less that 1/3 of the original image size (1/3^2 ~= .111), 450 * unless we would be resampling to a scale smaller than 128x128. 451 */ 452 if ( is_callable( array( $this->image, 'sampleImage' ) ) ) { 453 $resize_ratio = ( $dst_w / $this->size['width'] ) * ( $dst_h / $this->size['height'] ); 454 $sample_factor = 5; 455 456 if ( $resize_ratio < .111 && ( $dst_w * $sample_factor > 128 && $dst_h * $sample_factor > 128 ) ) { 457 $this->image->sampleImage( $dst_w * $sample_factor, $dst_h * $sample_factor ); 458 } 459 } 460 461 /* 462 * Use resizeImage() when it's available and a valid filter value is set. 463 * Otherwise, fall back to the scaleImage() method for resizing, which 464 * results in better image quality over resizeImage() with default filter 465 * settings and retains backward compatibility with pre 4.5 functionality. 466 */ 467 if ( is_callable( array( $this->image, 'resizeImage' ) ) && $filter ) { 468 $this->image->setOption( 'filter:support', '2.0' ); 469 $this->image->resizeImage( $dst_w, $dst_h, $filter, 1 ); 470 } else { 471 $this->image->scaleImage( $dst_w, $dst_h ); 472 } 473 474 // Set appropriate quality settings after resizing. 475 if ( 'image/jpeg' === $this->mime_type ) { 476 if ( is_callable( array( $this->image, 'unsharpMaskImage' ) ) ) { 477 $this->image->unsharpMaskImage( 0.25, 0.25, 8, 0.065 ); 478 } 479 480 $this->image->setOption( 'jpeg:fancy-upsampling', 'off' ); 481 } 482 483 if ( 'image/png' === $this->mime_type ) { 484 $this->image->setOption( 'png:compression-filter', '5' ); 485 $this->image->setOption( 'png:compression-level', '9' ); 486 $this->image->setOption( 'png:compression-strategy', '1' ); 487 488 // Indexed PNG files get some additional handling. 489 // See #63448 for details. 490 if ( 491 is_callable( array( $this->image, 'getImageProperty' ) ) 492 && '3' === $this->image->getImageProperty( 'png:IHDR.color-type-orig' ) 493 ) { 494 495 // Check for an alpha channel. 496 if ( 497 is_callable( array( $this->image, 'getImageAlphaChannel' ) ) 498 && $this->image->getImageAlphaChannel() 499 ) { 500 $this->image->setOption( 'png:include-chunk', 'tRNS' ); 501 } else { 502 $this->image->setOption( 'png:exclude-chunk', 'all' ); 503 } 504 // Set the image format to Indexed PNG. 505 $this->image->setOption( 'png:format', 'png8' ); 506 507 } else { 508 $this->image->setOption( 'png:exclude-chunk', 'all' ); 509 } 510 } 511 512 /* 513 * If alpha channel is not defined, set it opaque. 514 * 515 * Note that Imagick::getImageAlphaChannel() is only available if Imagick 516 * has been compiled against ImageMagick version 6.4.0 or newer. 517 */ 518 if ( is_callable( array( $this->image, 'getImageAlphaChannel' ) ) 519 && is_callable( array( $this->image, 'setImageAlphaChannel' ) ) 520 && defined( 'Imagick::ALPHACHANNEL_UNDEFINED' ) 521 && defined( 'Imagick::ALPHACHANNEL_OPAQUE' ) 522 ) { 523 if ( $this->image->getImageAlphaChannel() === Imagick::ALPHACHANNEL_UNDEFINED ) { 524 $this->image->setImageAlphaChannel( Imagick::ALPHACHANNEL_OPAQUE ); 525 } 526 } 527 528 // Limit the bit depth of resized images. 529 if ( is_callable( array( $this->image, 'getImageDepth' ) ) && is_callable( array( $this->image, 'setImageDepth' ) ) ) { 530 /** 531 * Filters the maximum bit depth of resized images. 532 * 533 * This filter only applies when resizing using the Imagick editor since GD 534 * does not support getting or setting bit depth. 535 * 536 * Use this to adjust the maximum bit depth of resized images. 537 * 538 * @since 6.8.0 539 * 540 * @param int $max_depth The maximum bit depth. Default is the input depth. 541 * @param int $image_depth The bit depth of the original image. 542 */ 543 $max_depth = apply_filters( 'image_max_bit_depth', $this->image->getImageDepth(), $this->image->getImageDepth() ); 544 $this->image->setImageDepth( $max_depth ); 545 } 546 } catch ( Exception $e ) { 547 return new WP_Error( 'image_resize_error', $e->getMessage() ); 548 } 549 } 550 551 /** 552 * Create multiple smaller images from a single source. 553 * 554 * Attempts to create all sub-sizes and returns the meta data at the end. This 555 * may result in the server running out of resources. When it fails there may be few 556 * "orphaned" images left over as the meta data is never returned and saved. 557 * 558 * As of 5.3.0 the preferred way to do this is with `make_subsize()`. It creates 559 * the new images one at a time and allows for the meta data to be saved after 560 * each new image is created. 561 * 562 * @since 3.5.0 563 * 564 * @param array $sizes { 565 * An array of image size data arrays. 566 * 567 * Either a height or width must be provided. 568 * If one of the two is set to null, the resize will 569 * maintain aspect ratio according to the provided dimension. 570 * 571 * @type array ...$0 { 572 * Array of height, width values, and whether to crop. 573 * 574 * @type int $width Image width. Optional if `$height` is specified. 575 * @type int $height Image height. Optional if `$width` is specified. 576 * @type bool|array $crop Optional. Whether to crop the image. Default false. 577 * } 578 * } 579 * @return array An array of resized images' metadata by size. 580 */ 581 public function multi_resize( $sizes ) { 582 $metadata = array(); 583 584 foreach ( $sizes as $size => $size_data ) { 585 $meta = $this->make_subsize( $size_data ); 586 587 if ( ! is_wp_error( $meta ) ) { 588 $metadata[ $size ] = $meta; 589 } 590 } 591 592 return $metadata; 593 } 594 595 /** 596 * Create an image sub-size and return the image meta data value for it. 597 * 598 * @since 5.3.0 599 * 600 * @param array $size_data { 601 * Array of size data. 602 * 603 * @type int $width The maximum width in pixels. 604 * @type int $height The maximum height in pixels. 605 * @type bool|array $crop Whether to crop the image to exact dimensions. 606 * } 607 * @return array|WP_Error The image data array for inclusion in the `sizes` array in the image meta, 608 * WP_Error object on error. 609 */ 610 public function make_subsize( $size_data ) { 611 if ( ! isset( $size_data['width'] ) && ! isset( $size_data['height'] ) ) { 612 return new WP_Error( 'image_subsize_create_error', __( 'Cannot resize the image. Both width and height are not set.' ) ); 613 } 614 615 $orig_size = $this->size; 616 $orig_image = $this->image->getImage(); 617 618 if ( ! isset( $size_data['width'] ) ) { 619 $size_data['width'] = null; 620 } 621 622 if ( ! isset( $size_data['height'] ) ) { 623 $size_data['height'] = null; 624 } 625 626 if ( ! isset( $size_data['crop'] ) ) { 627 $size_data['crop'] = false; 628 } 629 630 if ( ( $this->size['width'] === $size_data['width'] ) && ( $this->size['height'] === $size_data['height'] ) ) { 631 return new WP_Error( 'image_subsize_create_error', __( 'The image already has the requested size.' ) ); 632 } 633 634 $resized = $this->resize( $size_data['width'], $size_data['height'], $size_data['crop'] ); 635 636 if ( is_wp_error( $resized ) ) { 637 $saved = $resized; 638 } else { 639 $saved = $this->_save( $this->image ); 640 641 $this->image->clear(); 642 $this->image->destroy(); 643 $this->image = null; 644 } 645 646 $this->size = $orig_size; 647 $this->image = $orig_image; 648 649 if ( ! is_wp_error( $saved ) ) { 650 unset( $saved['path'] ); 651 } 652 653 return $saved; 654 } 655 656 /** 657 * Crops Image. 658 * 659 * @since 3.5.0 660 * 661 * @param int $src_x The start x position to crop from. 662 * @param int $src_y The start y position to crop from. 663 * @param int $src_w The width to crop. 664 * @param int $src_h The height to crop. 665 * @param int $dst_w Optional. The destination width. 666 * @param int $dst_h Optional. The destination height. 667 * @param bool $src_abs Optional. If the source crop points are absolute. 668 * @return true|WP_Error 669 */ 670 public function crop( $src_x, $src_y, $src_w, $src_h, $dst_w = null, $dst_h = null, $src_abs = false ) { 671 if ( $src_abs ) { 672 $src_w -= $src_x; 673 $src_h -= $src_y; 674 } 675 676 try { 677 $this->image->cropImage( $src_w, $src_h, $src_x, $src_y ); 678 $this->image->setImagePage( $src_w, $src_h, 0, 0 ); 679 680 if ( $dst_w || $dst_h ) { 681 /* 682 * If destination width/height isn't specified, 683 * use same as width/height from source. 684 */ 685 if ( ! $dst_w ) { 686 $dst_w = $src_w; 687 } 688 if ( ! $dst_h ) { 689 $dst_h = $src_h; 690 } 691 692 $thumb_result = $this->thumbnail_image( $dst_w, $dst_h ); 693 if ( is_wp_error( $thumb_result ) ) { 694 return $thumb_result; 695 } 696 697 return $this->update_size(); 698 } 699 } catch ( Exception $e ) { 700 return new WP_Error( 'image_crop_error', $e->getMessage() ); 701 } 702 703 return $this->update_size(); 704 } 705 706 /** 707 * Rotates current image counter-clockwise by $angle. 708 * 709 * @since 3.5.0 710 * 711 * @param float $angle 712 * @return true|WP_Error 713 */ 714 public function rotate( $angle ) { 715 /** 716 * $angle is 360-$angle because Imagick rotates clockwise 717 * (GD rotates counter-clockwise) 718 */ 719 try { 720 $this->image->rotateImage( new ImagickPixel( 'none' ), 360 - $angle ); 721 722 // Normalize EXIF orientation data so that display is consistent across devices. 723 if ( is_callable( array( $this->image, 'setImageOrientation' ) ) && defined( 'Imagick::ORIENTATION_TOPLEFT' ) ) { 724 $this->image->setImageOrientation( Imagick::ORIENTATION_TOPLEFT ); 725 } 726 727 // Since this changes the dimensions of the image, update the size. 728 $result = $this->update_size(); 729 if ( is_wp_error( $result ) ) { 730 return $result; 731 } 732 733 $this->image->setImagePage( $this->size['width'], $this->size['height'], 0, 0 ); 734 } catch ( Exception $e ) { 735 return new WP_Error( 'image_rotate_error', $e->getMessage() ); 736 } 737 738 return true; 739 } 740 741 /** 742 * Flips current image. 743 * 744 * @since 3.5.0 745 * 746 * @param bool $horz Flip along Horizontal Axis 747 * @param bool $vert Flip along Vertical Axis 748 * @return true|WP_Error 749 */ 750 public function flip( $horz, $vert ) { 751 try { 752 if ( $horz ) { 753 $this->image->flipImage(); 754 } 755 756 if ( $vert ) { 757 $this->image->flopImage(); 758 } 759 760 // Normalize EXIF orientation data so that display is consistent across devices. 761 if ( is_callable( array( $this->image, 'setImageOrientation' ) ) && defined( 'Imagick::ORIENTATION_TOPLEFT' ) ) { 762 $this->image->setImageOrientation( Imagick::ORIENTATION_TOPLEFT ); 763 } 764 } catch ( Exception $e ) { 765 return new WP_Error( 'image_flip_error', $e->getMessage() ); 766 } 767 768 return true; 769 } 770 771 /** 772 * Check if a JPEG image has EXIF Orientation tag and rotate it if needed. 773 * 774 * As ImageMagick copies the EXIF data to the flipped/rotated image, proceed only 775 * if EXIF Orientation can be reset afterwards. 776 * 777 * @since 5.3.0 778 * 779 * @return bool|WP_Error True if the image was rotated. False if no EXIF data or if the image doesn't need rotation. 780 * WP_Error if error while rotating. 781 */ 782 public function maybe_exif_rotate() { 783 if ( is_callable( array( $this->image, 'setImageOrientation' ) ) && defined( 'Imagick::ORIENTATION_TOPLEFT' ) ) { 784 return parent::maybe_exif_rotate(); 785 } else { 786 return new WP_Error( 'write_exif_error', __( 'The image cannot be rotated because the embedded meta data cannot be updated.' ) ); 787 } 788 } 789 790 /** 791 * Saves current image to file. 792 * 793 * @since 3.5.0 794 * @since 6.0.0 The `$filesize` value was added to the returned array. 795 * 796 * @param string $destfilename Optional. Destination filename. Default null. 797 * @param string $mime_type Optional. The mime-type. Default null. 798 * @return array|WP_Error { 799 * Array on success or WP_Error if the file failed to save. 800 * 801 * @type string $path Path to the image file. 802 * @type string $file Name of the image file. 803 * @type int $width Image width. 804 * @type int $height Image height. 805 * @type string $mime-type The mime type of the image. 806 * @type int $filesize File size of the image. 807 * } 808 */ 809 public function save( $destfilename = null, $mime_type = null ) { 810 $saved = $this->_save( $this->image, $destfilename, $mime_type ); 811 812 if ( ! is_wp_error( $saved ) ) { 813 $this->file = $saved['path']; 814 $this->mime_type = $saved['mime-type']; 815 816 try { 817 $this->image->setImageFormat( strtoupper( $this->get_extension( $this->mime_type ) ) ); 818 } catch ( Exception $e ) { 819 return new WP_Error( 'image_save_error', $e->getMessage(), $this->file ); 820 } 821 } 822 823 return $saved; 824 } 825 826 /** 827 * Removes PDF alpha after it's been read. 828 * 829 * @since 6.4.0 830 */ 831 protected function remove_pdf_alpha_channel() { 832 $version = Imagick::getVersion(); 833 // Remove alpha channel if possible to avoid black backgrounds for Ghostscript >= 9.14. RemoveAlphaChannel added in ImageMagick 6.7.5. 834 if ( $version['versionNumber'] >= 0x675 ) { 835 try { 836 // Imagick::ALPHACHANNEL_REMOVE mapped to RemoveAlphaChannel in PHP imagick 3.2.0b2. 837 $this->image->setImageAlphaChannel( defined( 'Imagick::ALPHACHANNEL_REMOVE' ) ? Imagick::ALPHACHANNEL_REMOVE : 12 ); 838 } catch ( Exception $e ) { 839 return new WP_Error( 'pdf_alpha_process_failed', $e->getMessage() ); 840 } 841 } 842 } 843 844 /** 845 * @since 3.5.0 846 * @since 6.0.0 The `$filesize` value was added to the returned array. 847 * 848 * @param Imagick $image 849 * @param string $filename 850 * @param string $mime_type 851 * @return array|WP_Error { 852 * Array on success or WP_Error if the file failed to save. 853 * 854 * @type string $path Path to the image file. 855 * @type string $file Name of the image file. 856 * @type int $width Image width. 857 * @type int $height Image height. 858 * @type string $mime-type The mime type of the image. 859 * @type int $filesize File size of the image. 860 * } 861 */ 862 protected function _save( $image, $filename = null, $mime_type = null ) { 863 list( $filename, $extension, $mime_type ) = $this->get_output_format( $filename, $mime_type ); 864 865 if ( ! $filename ) { 866 $filename = $this->generate_filename( null, null, $extension ); 867 } 868 869 try { 870 // Store initial format. 871 $orig_format = $this->image->getImageFormat(); 872 873 $this->image->setImageFormat( strtoupper( $this->get_extension( $mime_type ) ) ); 874 } catch ( Exception $e ) { 875 return new WP_Error( 'image_save_error', $e->getMessage(), $filename ); 876 } 877 878 if ( method_exists( $this->image, 'setInterlaceScheme' ) 879 && method_exists( $this->image, 'getInterlaceScheme' ) 880 && defined( 'Imagick::INTERLACE_PLANE' ) 881 ) { 882 $orig_interlace = $this->image->getInterlaceScheme(); 883 884 /** This filter is documented in wp-includes/class-wp-image-editor-gd.php */ 885 if ( apply_filters( 'image_save_progressive', false, $mime_type ) ) { 886 $this->image->setInterlaceScheme( Imagick::INTERLACE_PLANE ); // True - line interlace output. 887 } else { 888 $this->image->setInterlaceScheme( Imagick::INTERLACE_NO ); // False - no interlace output. 889 } 890 } 891 892 $write_image_result = $this->write_image( $this->image, $filename ); 893 if ( is_wp_error( $write_image_result ) ) { 894 return $write_image_result; 895 } 896 897 try { 898 // Reset original format. 899 $this->image->setImageFormat( $orig_format ); 900 901 if ( isset( $orig_interlace ) ) { 902 $this->image->setInterlaceScheme( $orig_interlace ); 903 } 904 } catch ( Exception $e ) { 905 return new WP_Error( 'image_save_error', $e->getMessage(), $filename ); 906 } 907 908 // Set correct file permissions. 909 $stat = stat( dirname( $filename ) ); 910 $perms = $stat['mode'] & 0000666; // Same permissions as parent folder, strip off the executable bits. 911 chmod( $filename, $perms ); 912 913 return array( 914 'path' => $filename, 915 /** This filter is documented in wp-includes/class-wp-image-editor-gd.php */ 916 'file' => wp_basename( apply_filters( 'image_make_intermediate_size', $filename ) ), 917 'width' => $this->size['width'], 918 'height' => $this->size['height'], 919 'mime-type' => $mime_type, 920 'filesize' => wp_filesize( $filename ), 921 ); 922 } 923 924 /** 925 * Writes an image to a file or stream. 926 * 927 * @since 5.6.0 928 * 929 * @param Imagick $image 930 * @param string $filename The destination filename or stream URL. 931 * @return true|WP_Error 932 */ 933 private function write_image( $image, $filename ) { 934 if ( wp_is_stream( $filename ) ) { 935 /* 936 * Due to reports of issues with streams with `Imagick::writeImageFile()` and `Imagick::writeImage()`, copies the blob instead. 937 * Checks for exact type due to: https://www.php.net/manual/en/function.file-put-contents.php 938 */ 939 if ( file_put_contents( $filename, $image->getImageBlob() ) === false ) { 940 return new WP_Error( 941 'image_save_error', 942 sprintf( 943 /* translators: %s: PHP function name. */ 944 __( '%s failed while writing image to stream.' ), 945 '<code>file_put_contents()</code>' 946 ), 947 $filename 948 ); 949 } else { 950 return true; 951 } 952 } else { 953 $dirname = dirname( $filename ); 954 955 if ( ! wp_mkdir_p( $dirname ) ) { 956 return new WP_Error( 957 'image_save_error', 958 sprintf( 959 /* translators: %s: Directory path. */ 960 __( 'Unable to create directory %s. Is its parent directory writable by the server?' ), 961 esc_html( $dirname ) 962 ) 963 ); 964 } 965 966 try { 967 return $image->writeImage( $filename ); 968 } catch ( Exception $e ) { 969 return new WP_Error( 'image_save_error', $e->getMessage(), $filename ); 970 } 971 } 972 } 973 974 /** 975 * Streams current image to browser. 976 * 977 * @since 3.5.0 978 * 979 * @param string $mime_type The mime type of the image. 980 * @return true|WP_Error True on success, WP_Error object on failure. 981 */ 982 public function stream( $mime_type = null ) { 983 list( $filename, $extension, $mime_type ) = $this->get_output_format( null, $mime_type ); 984 985 try { 986 // Temporarily change format for stream. 987 $this->image->setImageFormat( strtoupper( $extension ) ); 988 989 // Output stream of image content. 990 header( "Content-Type: $mime_type" ); 991 print $this->image->getImageBlob(); 992 993 // Reset image to original format. 994 $this->image->setImageFormat( $this->get_extension( $this->mime_type ) ); 995 } catch ( Exception $e ) { 996 return new WP_Error( 'image_stream_error', $e->getMessage() ); 997 } 998 999 return true; 1000 } 1001 1002 /** 1003 * Strips all image meta except color profiles from an image. 1004 * 1005 * @since 4.5.0 1006 * 1007 * @return true|WP_Error True if stripping metadata was successful. WP_Error object on error. 1008 */ 1009 protected function strip_meta() { 1010 1011 if ( ! is_callable( array( $this->image, 'getImageProfiles' ) ) ) { 1012 return new WP_Error( 1013 'image_strip_meta_error', 1014 sprintf( 1015 /* translators: %s: ImageMagick method name. */ 1016 __( '%s is required to strip image meta.' ), 1017 '<code>Imagick::getImageProfiles()</code>' 1018 ) 1019 ); 1020 } 1021 1022 if ( ! is_callable( array( $this->image, 'removeImageProfile' ) ) ) { 1023 return new WP_Error( 1024 'image_strip_meta_error', 1025 sprintf( 1026 /* translators: %s: ImageMagick method name. */ 1027 __( '%s is required to strip image meta.' ), 1028 '<code>Imagick::removeImageProfile()</code>' 1029 ) 1030 ); 1031 } 1032 1033 /* 1034 * Protect a few profiles from being stripped for the following reasons: 1035 * 1036 * - icc: Color profile information 1037 * - icm: Color profile information 1038 * - iptc: Copyright data 1039 * - exif: Orientation data 1040 * - xmp: Rights usage data 1041 */ 1042 $protected_profiles = array( 1043 'icc', 1044 'icm', 1045 'iptc', 1046 'exif', 1047 'xmp', 1048 ); 1049 1050 try { 1051 // Strip profiles. 1052 foreach ( $this->image->getImageProfiles( '*', true ) as $key => $value ) { 1053 if ( ! in_array( $key, $protected_profiles, true ) ) { 1054 $this->image->removeImageProfile( $key ); 1055 } 1056 } 1057 } catch ( Exception $e ) { 1058 return new WP_Error( 'image_strip_meta_error', $e->getMessage() ); 1059 } 1060 1061 return true; 1062 } 1063 1064 /** 1065 * Sets up Imagick for PDF processing. 1066 * Increases rendering DPI and only loads first page. 1067 * 1068 * @since 4.7.0 1069 * 1070 * @return string|WP_Error File to load or WP_Error on failure. 1071 */ 1072 protected function pdf_setup() { 1073 try { 1074 /* 1075 * By default, PDFs are rendered in a very low resolution. 1076 * We want the thumbnail to be readable, so increase the rendering DPI. 1077 */ 1078 $this->image->setResolution( 128, 128 ); 1079 1080 // Only load the first page. 1081 return $this->file . '[0]'; 1082 } catch ( Exception $e ) { 1083 return new WP_Error( 'pdf_setup_failed', $e->getMessage(), $this->file ); 1084 } 1085 } 1086 1087 /** 1088 * Load the image produced by Ghostscript. 1089 * 1090 * Includes a workaround for a bug in Ghostscript 8.70 that prevents processing of some PDF files 1091 * when `use-cropbox` is set. 1092 * 1093 * @since 5.6.0 1094 * 1095 * @return true|WP_Error 1096 */ 1097 protected function pdf_load_source() { 1098 $filename = $this->pdf_setup(); 1099 1100 if ( is_wp_error( $filename ) ) { 1101 return $filename; 1102 } 1103 1104 try { 1105 /* 1106 * When generating thumbnails from cropped PDF pages, Imagemagick uses the uncropped 1107 * area (resulting in unnecessary whitespace) unless the following option is set. 1108 */ 1109 $this->image->setOption( 'pdf:use-cropbox', true ); 1110 1111 /* 1112 * Reading image after Imagick instantiation because `setResolution` 1113 * only applies correctly before the image is read. 1114 */ 1115 $this->image->readImage( $filename ); 1116 } catch ( Exception $e ) { 1117 // Attempt to run `gs` without the `use-cropbox` option. See #48853. 1118 $this->image->setOption( 'pdf:use-cropbox', false ); 1119 1120 $this->image->readImage( $filename ); 1121 } 1122 1123 return true; 1124 } 1125 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
Generated : Sat Jun 7 08:20:01 2025 | Cross-referenced by PHPXref |