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