[ 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 // Check to see if a PNG is indexed, and find the pixel depth. 488 if ( is_callable( array( $this->image, 'getImageDepth' ) ) ) { 489 $indexed_pixel_depth = $this->image->getImageDepth(); 490 491 // Indexed PNG files get some additional handling. 492 if ( 0 < $indexed_pixel_depth && 8 >= $indexed_pixel_depth ) { 493 // Check for an alpha channel. 494 if ( 495 is_callable( array( $this->image, 'getImageAlphaChannel' ) ) 496 && $this->image->getImageAlphaChannel() 497 ) { 498 $this->image->setOption( 'png:include-chunk', 'tRNS' ); 499 } else { 500 $this->image->setOption( 'png:exclude-chunk', 'all' ); 501 } 502 503 // Reduce colors in the images to maximum needed, using the global colorspace. 504 $max_colors = pow( 2, $indexed_pixel_depth ); 505 if ( is_callable( array( $this->image, 'getImageColors' ) ) ) { 506 $current_colors = $this->image->getImageColors(); 507 $max_colors = min( $max_colors, $current_colors ); 508 } 509 $this->image->quantizeImage( $max_colors, $this->image->getColorspace(), 0, false, false ); 510 511 /** 512 * If the colorspace is 'gray', use the png8 format to ensure it stays indexed. 513 */ 514 if ( Imagick::COLORSPACE_GRAY === $this->image->getImageColorspace() ) { 515 $this->image->setOption( 'png:format', 'png8' ); 516 } 517 } 518 } 519 } 520 521 /* 522 * If alpha channel is not defined, set it opaque. 523 * 524 * Note that Imagick::getImageAlphaChannel() is only available if Imagick 525 * has been compiled against ImageMagick version 6.4.0 or newer. 526 */ 527 if ( is_callable( array( $this->image, 'getImageAlphaChannel' ) ) 528 && is_callable( array( $this->image, 'setImageAlphaChannel' ) ) 529 && defined( 'Imagick::ALPHACHANNEL_UNDEFINED' ) 530 && defined( 'Imagick::ALPHACHANNEL_OPAQUE' ) 531 ) { 532 if ( $this->image->getImageAlphaChannel() === Imagick::ALPHACHANNEL_UNDEFINED ) { 533 $this->image->setImageAlphaChannel( Imagick::ALPHACHANNEL_OPAQUE ); 534 } 535 } 536 537 // Limit the bit depth of resized images. 538 if ( is_callable( array( $this->image, 'getImageDepth' ) ) && is_callable( array( $this->image, 'setImageDepth' ) ) ) { 539 /** 540 * Filters the maximum bit depth of resized images. 541 * 542 * This filter only applies when resizing using the Imagick editor since GD 543 * does not support getting or setting bit depth. 544 * 545 * Use this to adjust the maximum bit depth of resized images. 546 * 547 * @since 6.8.0 548 * 549 * @param int $max_depth The maximum bit depth. Default is the input depth. 550 * @param int $image_depth The bit depth of the original image. 551 */ 552 $max_depth = apply_filters( 'image_max_bit_depth', $this->image->getImageDepth(), $this->image->getImageDepth() ); 553 $this->image->setImageDepth( $max_depth ); 554 } 555 } catch ( Exception $e ) { 556 return new WP_Error( 'image_resize_error', $e->getMessage() ); 557 } 558 } 559 560 /** 561 * Create multiple smaller images from a single source. 562 * 563 * Attempts to create all sub-sizes and returns the meta data at the end. This 564 * may result in the server running out of resources. When it fails there may be few 565 * "orphaned" images left over as the meta data is never returned and saved. 566 * 567 * As of 5.3.0 the preferred way to do this is with `make_subsize()`. It creates 568 * the new images one at a time and allows for the meta data to be saved after 569 * each new image is created. 570 * 571 * @since 3.5.0 572 * 573 * @param array $sizes { 574 * An array of image size data arrays. 575 * 576 * Either a height or width must be provided. 577 * If one of the two is set to null, the resize will 578 * maintain aspect ratio according to the provided dimension. 579 * 580 * @type array ...$0 { 581 * Array of height, width values, and whether to crop. 582 * 583 * @type int $width Image width. Optional if `$height` is specified. 584 * @type int $height Image height. Optional if `$width` is specified. 585 * @type bool|array $crop Optional. Whether to crop the image. Default false. 586 * } 587 * } 588 * @return array An array of resized images' metadata by size. 589 */ 590 public function multi_resize( $sizes ) { 591 $metadata = array(); 592 593 foreach ( $sizes as $size => $size_data ) { 594 $meta = $this->make_subsize( $size_data ); 595 596 if ( ! is_wp_error( $meta ) ) { 597 $metadata[ $size ] = $meta; 598 } 599 } 600 601 return $metadata; 602 } 603 604 /** 605 * Create an image sub-size and return the image meta data value for it. 606 * 607 * @since 5.3.0 608 * 609 * @param array $size_data { 610 * Array of size data. 611 * 612 * @type int $width The maximum width in pixels. 613 * @type int $height The maximum height in pixels. 614 * @type bool|array $crop Whether to crop the image to exact dimensions. 615 * } 616 * @return array|WP_Error The image data array for inclusion in the `sizes` array in the image meta, 617 * WP_Error object on error. 618 */ 619 public function make_subsize( $size_data ) { 620 if ( ! isset( $size_data['width'] ) && ! isset( $size_data['height'] ) ) { 621 return new WP_Error( 'image_subsize_create_error', __( 'Cannot resize the image. Both width and height are not set.' ) ); 622 } 623 624 $orig_size = $this->size; 625 $orig_image = $this->image->getImage(); 626 627 if ( ! isset( $size_data['width'] ) ) { 628 $size_data['width'] = null; 629 } 630 631 if ( ! isset( $size_data['height'] ) ) { 632 $size_data['height'] = null; 633 } 634 635 if ( ! isset( $size_data['crop'] ) ) { 636 $size_data['crop'] = false; 637 } 638 639 if ( ( $this->size['width'] === $size_data['width'] ) && ( $this->size['height'] === $size_data['height'] ) ) { 640 return new WP_Error( 'image_subsize_create_error', __( 'The image already has the requested size.' ) ); 641 } 642 643 $resized = $this->resize( $size_data['width'], $size_data['height'], $size_data['crop'] ); 644 645 if ( is_wp_error( $resized ) ) { 646 $saved = $resized; 647 } else { 648 $saved = $this->_save( $this->image ); 649 650 $this->image->clear(); 651 $this->image->destroy(); 652 $this->image = null; 653 } 654 655 $this->size = $orig_size; 656 $this->image = $orig_image; 657 658 if ( ! is_wp_error( $saved ) ) { 659 unset( $saved['path'] ); 660 } 661 662 return $saved; 663 } 664 665 /** 666 * Crops Image. 667 * 668 * @since 3.5.0 669 * 670 * @param int $src_x The start x position to crop from. 671 * @param int $src_y The start y position to crop from. 672 * @param int $src_w The width to crop. 673 * @param int $src_h The height to crop. 674 * @param int $dst_w Optional. The destination width. 675 * @param int $dst_h Optional. The destination height. 676 * @param bool $src_abs Optional. If the source crop points are absolute. 677 * @return true|WP_Error 678 */ 679 public function crop( $src_x, $src_y, $src_w, $src_h, $dst_w = null, $dst_h = null, $src_abs = false ) { 680 if ( $src_abs ) { 681 $src_w -= $src_x; 682 $src_h -= $src_y; 683 } 684 685 try { 686 $this->image->cropImage( $src_w, $src_h, $src_x, $src_y ); 687 $this->image->setImagePage( $src_w, $src_h, 0, 0 ); 688 689 if ( $dst_w || $dst_h ) { 690 /* 691 * If destination width/height isn't specified, 692 * use same as width/height from source. 693 */ 694 if ( ! $dst_w ) { 695 $dst_w = $src_w; 696 } 697 if ( ! $dst_h ) { 698 $dst_h = $src_h; 699 } 700 701 $thumb_result = $this->thumbnail_image( $dst_w, $dst_h ); 702 if ( is_wp_error( $thumb_result ) ) { 703 return $thumb_result; 704 } 705 706 return $this->update_size(); 707 } 708 } catch ( Exception $e ) { 709 return new WP_Error( 'image_crop_error', $e->getMessage() ); 710 } 711 712 return $this->update_size(); 713 } 714 715 /** 716 * Rotates current image counter-clockwise by $angle. 717 * 718 * @since 3.5.0 719 * 720 * @param float $angle 721 * @return true|WP_Error 722 */ 723 public function rotate( $angle ) { 724 /** 725 * $angle is 360-$angle because Imagick rotates clockwise 726 * (GD rotates counter-clockwise) 727 */ 728 try { 729 $this->image->rotateImage( new ImagickPixel( 'none' ), 360 - $angle ); 730 731 // Normalize EXIF orientation data so that display is consistent across devices. 732 if ( is_callable( array( $this->image, 'setImageOrientation' ) ) && defined( 'Imagick::ORIENTATION_TOPLEFT' ) ) { 733 $this->image->setImageOrientation( Imagick::ORIENTATION_TOPLEFT ); 734 } 735 736 // Since this changes the dimensions of the image, update the size. 737 $result = $this->update_size(); 738 if ( is_wp_error( $result ) ) { 739 return $result; 740 } 741 742 $this->image->setImagePage( $this->size['width'], $this->size['height'], 0, 0 ); 743 } catch ( Exception $e ) { 744 return new WP_Error( 'image_rotate_error', $e->getMessage() ); 745 } 746 747 return true; 748 } 749 750 /** 751 * Flips current image. 752 * 753 * @since 3.5.0 754 * 755 * @param bool $horz Flip along Horizontal Axis 756 * @param bool $vert Flip along Vertical Axis 757 * @return true|WP_Error 758 */ 759 public function flip( $horz, $vert ) { 760 try { 761 if ( $horz ) { 762 $this->image->flipImage(); 763 } 764 765 if ( $vert ) { 766 $this->image->flopImage(); 767 } 768 769 // Normalize EXIF orientation data so that display is consistent across devices. 770 if ( is_callable( array( $this->image, 'setImageOrientation' ) ) && defined( 'Imagick::ORIENTATION_TOPLEFT' ) ) { 771 $this->image->setImageOrientation( Imagick::ORIENTATION_TOPLEFT ); 772 } 773 } catch ( Exception $e ) { 774 return new WP_Error( 'image_flip_error', $e->getMessage() ); 775 } 776 777 return true; 778 } 779 780 /** 781 * Check if a JPEG image has EXIF Orientation tag and rotate it if needed. 782 * 783 * As ImageMagick copies the EXIF data to the flipped/rotated image, proceed only 784 * if EXIF Orientation can be reset afterwards. 785 * 786 * @since 5.3.0 787 * 788 * @return bool|WP_Error True if the image was rotated. False if no EXIF data or if the image doesn't need rotation. 789 * WP_Error if error while rotating. 790 */ 791 public function maybe_exif_rotate() { 792 if ( is_callable( array( $this->image, 'setImageOrientation' ) ) && defined( 'Imagick::ORIENTATION_TOPLEFT' ) ) { 793 return parent::maybe_exif_rotate(); 794 } else { 795 return new WP_Error( 'write_exif_error', __( 'The image cannot be rotated because the embedded meta data cannot be updated.' ) ); 796 } 797 } 798 799 /** 800 * Saves current image to file. 801 * 802 * @since 3.5.0 803 * @since 6.0.0 The `$filesize` value was added to the returned array. 804 * 805 * @param string $destfilename Optional. Destination filename. Default null. 806 * @param string $mime_type Optional. The mime-type. Default null. 807 * @return array|WP_Error { 808 * Array on success or WP_Error if the file failed to save. 809 * 810 * @type string $path Path to the image file. 811 * @type string $file Name of the image file. 812 * @type int $width Image width. 813 * @type int $height Image height. 814 * @type string $mime-type The mime type of the image. 815 * @type int $filesize File size of the image. 816 * } 817 */ 818 public function save( $destfilename = null, $mime_type = null ) { 819 $saved = $this->_save( $this->image, $destfilename, $mime_type ); 820 821 if ( ! is_wp_error( $saved ) ) { 822 $this->file = $saved['path']; 823 $this->mime_type = $saved['mime-type']; 824 825 try { 826 $this->image->setImageFormat( strtoupper( $this->get_extension( $this->mime_type ) ) ); 827 } catch ( Exception $e ) { 828 return new WP_Error( 'image_save_error', $e->getMessage(), $this->file ); 829 } 830 } 831 832 return $saved; 833 } 834 835 /** 836 * Removes PDF alpha after it's been read. 837 * 838 * @since 6.4.0 839 */ 840 protected function remove_pdf_alpha_channel() { 841 $version = Imagick::getVersion(); 842 // Remove alpha channel if possible to avoid black backgrounds for Ghostscript >= 9.14. RemoveAlphaChannel added in ImageMagick 6.7.5. 843 if ( $version['versionNumber'] >= 0x675 ) { 844 try { 845 // Imagick::ALPHACHANNEL_REMOVE mapped to RemoveAlphaChannel in PHP imagick 3.2.0b2. 846 $this->image->setImageAlphaChannel( defined( 'Imagick::ALPHACHANNEL_REMOVE' ) ? Imagick::ALPHACHANNEL_REMOVE : 12 ); 847 } catch ( Exception $e ) { 848 return new WP_Error( 'pdf_alpha_process_failed', $e->getMessage() ); 849 } 850 } 851 } 852 853 /** 854 * @since 3.5.0 855 * @since 6.0.0 The `$filesize` value was added to the returned array. 856 * 857 * @param Imagick $image 858 * @param string $filename 859 * @param string $mime_type 860 * @return array|WP_Error { 861 * Array on success or WP_Error if the file failed to save. 862 * 863 * @type string $path Path to the image file. 864 * @type string $file Name of the image file. 865 * @type int $width Image width. 866 * @type int $height Image height. 867 * @type string $mime-type The mime type of the image. 868 * @type int $filesize File size of the image. 869 * } 870 */ 871 protected function _save( $image, $filename = null, $mime_type = null ) { 872 list( $filename, $extension, $mime_type ) = $this->get_output_format( $filename, $mime_type ); 873 874 if ( ! $filename ) { 875 $filename = $this->generate_filename( null, null, $extension ); 876 } 877 878 try { 879 // Store initial format. 880 $orig_format = $this->image->getImageFormat(); 881 882 $this->image->setImageFormat( strtoupper( $this->get_extension( $mime_type ) ) ); 883 } catch ( Exception $e ) { 884 return new WP_Error( 'image_save_error', $e->getMessage(), $filename ); 885 } 886 887 if ( method_exists( $this->image, 'setInterlaceScheme' ) 888 && method_exists( $this->image, 'getInterlaceScheme' ) 889 && defined( 'Imagick::INTERLACE_PLANE' ) 890 ) { 891 $orig_interlace = $this->image->getInterlaceScheme(); 892 893 /** This filter is documented in wp-includes/class-wp-image-editor-gd.php */ 894 if ( apply_filters( 'image_save_progressive', false, $mime_type ) ) { 895 $this->image->setInterlaceScheme( Imagick::INTERLACE_PLANE ); // True - line interlace output. 896 } else { 897 $this->image->setInterlaceScheme( Imagick::INTERLACE_NO ); // False - no interlace output. 898 } 899 } 900 901 $write_image_result = $this->write_image( $this->image, $filename ); 902 if ( is_wp_error( $write_image_result ) ) { 903 return $write_image_result; 904 } 905 906 try { 907 // Reset original format. 908 $this->image->setImageFormat( $orig_format ); 909 910 if ( isset( $orig_interlace ) ) { 911 $this->image->setInterlaceScheme( $orig_interlace ); 912 } 913 } catch ( Exception $e ) { 914 return new WP_Error( 'image_save_error', $e->getMessage(), $filename ); 915 } 916 917 // Set correct file permissions. 918 $stat = stat( dirname( $filename ) ); 919 $perms = $stat['mode'] & 0000666; // Same permissions as parent folder, strip off the executable bits. 920 chmod( $filename, $perms ); 921 922 return array( 923 'path' => $filename, 924 /** This filter is documented in wp-includes/class-wp-image-editor-gd.php */ 925 'file' => wp_basename( apply_filters( 'image_make_intermediate_size', $filename ) ), 926 'width' => $this->size['width'], 927 'height' => $this->size['height'], 928 'mime-type' => $mime_type, 929 'filesize' => wp_filesize( $filename ), 930 ); 931 } 932 933 /** 934 * Writes an image to a file or stream. 935 * 936 * @since 5.6.0 937 * 938 * @param Imagick $image 939 * @param string $filename The destination filename or stream URL. 940 * @return true|WP_Error 941 */ 942 private function write_image( $image, $filename ) { 943 if ( wp_is_stream( $filename ) ) { 944 /* 945 * Due to reports of issues with streams with `Imagick::writeImageFile()` and `Imagick::writeImage()`, copies the blob instead. 946 * Checks for exact type due to: https://www.php.net/manual/en/function.file-put-contents.php 947 */ 948 if ( file_put_contents( $filename, $image->getImageBlob() ) === false ) { 949 return new WP_Error( 950 'image_save_error', 951 sprintf( 952 /* translators: %s: PHP function name. */ 953 __( '%s failed while writing image to stream.' ), 954 '<code>file_put_contents()</code>' 955 ), 956 $filename 957 ); 958 } else { 959 return true; 960 } 961 } else { 962 $dirname = dirname( $filename ); 963 964 if ( ! wp_mkdir_p( $dirname ) ) { 965 return new WP_Error( 966 'image_save_error', 967 sprintf( 968 /* translators: %s: Directory path. */ 969 __( 'Unable to create directory %s. Is its parent directory writable by the server?' ), 970 esc_html( $dirname ) 971 ) 972 ); 973 } 974 975 try { 976 return $image->writeImage( $filename ); 977 } catch ( Exception $e ) { 978 return new WP_Error( 'image_save_error', $e->getMessage(), $filename ); 979 } 980 } 981 } 982 983 /** 984 * Streams current image to browser. 985 * 986 * @since 3.5.0 987 * 988 * @param string $mime_type The mime type of the image. 989 * @return true|WP_Error True on success, WP_Error object on failure. 990 */ 991 public function stream( $mime_type = null ) { 992 list( $filename, $extension, $mime_type ) = $this->get_output_format( null, $mime_type ); 993 994 try { 995 // Temporarily change format for stream. 996 $this->image->setImageFormat( strtoupper( $extension ) ); 997 998 // Output stream of image content. 999 header( "Content-Type: $mime_type" ); 1000 print $this->image->getImageBlob(); 1001 1002 // Reset image to original format. 1003 $this->image->setImageFormat( $this->get_extension( $this->mime_type ) ); 1004 } catch ( Exception $e ) { 1005 return new WP_Error( 'image_stream_error', $e->getMessage() ); 1006 } 1007 1008 return true; 1009 } 1010 1011 /** 1012 * Strips all image meta except color profiles from an image. 1013 * 1014 * @since 4.5.0 1015 * 1016 * @return true|WP_Error True if stripping metadata was successful. WP_Error object on error. 1017 */ 1018 protected function strip_meta() { 1019 1020 if ( ! is_callable( array( $this->image, 'getImageProfiles' ) ) ) { 1021 return new WP_Error( 1022 'image_strip_meta_error', 1023 sprintf( 1024 /* translators: %s: ImageMagick method name. */ 1025 __( '%s is required to strip image meta.' ), 1026 '<code>Imagick::getImageProfiles()</code>' 1027 ) 1028 ); 1029 } 1030 1031 if ( ! is_callable( array( $this->image, 'removeImageProfile' ) ) ) { 1032 return new WP_Error( 1033 'image_strip_meta_error', 1034 sprintf( 1035 /* translators: %s: ImageMagick method name. */ 1036 __( '%s is required to strip image meta.' ), 1037 '<code>Imagick::removeImageProfile()</code>' 1038 ) 1039 ); 1040 } 1041 1042 /* 1043 * Protect a few profiles from being stripped for the following reasons: 1044 * 1045 * - icc: Color profile information 1046 * - icm: Color profile information 1047 * - iptc: Copyright data 1048 * - exif: Orientation data 1049 * - xmp: Rights usage data 1050 */ 1051 $protected_profiles = array( 1052 'icc', 1053 'icm', 1054 'iptc', 1055 'exif', 1056 'xmp', 1057 ); 1058 1059 try { 1060 // Strip profiles. 1061 foreach ( $this->image->getImageProfiles( '*', true ) as $key => $value ) { 1062 if ( ! in_array( $key, $protected_profiles, true ) ) { 1063 $this->image->removeImageProfile( $key ); 1064 } 1065 } 1066 } catch ( Exception $e ) { 1067 return new WP_Error( 'image_strip_meta_error', $e->getMessage() ); 1068 } 1069 1070 return true; 1071 } 1072 1073 /** 1074 * Sets up Imagick for PDF processing. 1075 * Increases rendering DPI and only loads first page. 1076 * 1077 * @since 4.7.0 1078 * 1079 * @return string|WP_Error File to load or WP_Error on failure. 1080 */ 1081 protected function pdf_setup() { 1082 try { 1083 /* 1084 * By default, PDFs are rendered in a very low resolution. 1085 * We want the thumbnail to be readable, so increase the rendering DPI. 1086 */ 1087 $this->image->setResolution( 128, 128 ); 1088 1089 // Only load the first page. 1090 return $this->file . '[0]'; 1091 } catch ( Exception $e ) { 1092 return new WP_Error( 'pdf_setup_failed', $e->getMessage(), $this->file ); 1093 } 1094 } 1095 1096 /** 1097 * Load the image produced by Ghostscript. 1098 * 1099 * Includes a workaround for a bug in Ghostscript 8.70 that prevents processing of some PDF files 1100 * when `use-cropbox` is set. 1101 * 1102 * @since 5.6.0 1103 * 1104 * @return true|WP_Error 1105 */ 1106 protected function pdf_load_source() { 1107 $filename = $this->pdf_setup(); 1108 1109 if ( is_wp_error( $filename ) ) { 1110 return $filename; 1111 } 1112 1113 try { 1114 /* 1115 * When generating thumbnails from cropped PDF pages, Imagemagick uses the uncropped 1116 * area (resulting in unnecessary whitespace) unless the following option is set. 1117 */ 1118 $this->image->setOption( 'pdf:use-cropbox', true ); 1119 1120 /* 1121 * Reading image after Imagick instantiation because `setResolution` 1122 * only applies correctly before the image is read. 1123 */ 1124 $this->image->readImage( $filename ); 1125 } catch ( Exception $e ) { 1126 // Attempt to run `gs` without the `use-cropbox` option. See #48853. 1127 $this->image->setOption( 'pdf:use-cropbox', false ); 1128 1129 $this->image->readImage( $filename ); 1130 } 1131 1132 return true; 1133 } 1134 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
Generated : Tue Jan 21 08:20:01 2025 | Cross-referenced by PHPXref |