From 39ee08c7cffa8a83d18c163598bbbee589369245 Mon Sep 17 00:00:00 2001 From: Nick Chomey Date: Sun, 15 Feb 2026 10:28:47 -0600 Subject: [PATCH 01/84] Add initial core VIPS integration, tests, and local-env hooks --- composer.json | 7 +- docker-compose.vips.yml | 7 + src/wp-admin/includes/class-wp-debug-data.php | 55 ++ .../includes/class-wp-site-health.php | 7 + .../class-wp-image-editor-vips.php | 599 ++++++++++++++++++ src/wp-includes/media.php | 5 +- src/wp-includes/update.php | 18 +- tests/phpunit/tests/image/editorVips.php | 224 +++++++ tests/phpunit/tests/image/functions.php | 3 +- tests/phpunit/tests/image/resizeVips.php | 27 + tools/local-env/php-vips/Dockerfile | 19 + tools/local-env/scripts/utils.js | 5 + 12 files changed, 970 insertions(+), 6 deletions(-) create mode 100644 docker-compose.vips.yml create mode 100644 src/wp-includes/class-wp-image-editor-vips.php create mode 100644 tests/phpunit/tests/image/editorVips.php create mode 100644 tests/phpunit/tests/image/resizeVips.php create mode 100644 tools/local-env/php-vips/Dockerfile diff --git a/composer.json b/composer.json index f61b6e5e72854..a95aeaa6f0927 100644 --- a/composer.json +++ b/composer.json @@ -13,7 +13,8 @@ "require": { "ext-hash": "*", "ext-json": "*", - "php": ">=7.4" + "php": ">=7.4", + "jcupitt/vips": "*" }, "suggest": { "ext-apcu": "*", @@ -21,6 +22,7 @@ "ext-curl": "*", "ext-dom": "*", "ext-exif": "*", + "ext-ffi": "Required to use the optional WP_Image_Editor_Vips backend", "ext-fileinfo": "*", "ext-filter": "*", "ext-ftp": "*", @@ -45,7 +47,8 @@ "ext-xml": "*", "ext-xmlreader": "*", "ext-zip": "*", - "ext-zlib": "*" + "ext-zlib": "*", + "jcupitt/vips": "Required to use the optional WP_Image_Editor_Vips backend" }, "require-dev": { "composer/ca-bundle": "1.5.13", diff --git a/docker-compose.vips.yml b/docker-compose.vips.yml new file mode 100644 index 0000000000000..26b6b98860125 --- /dev/null +++ b/docker-compose.vips.yml @@ -0,0 +1,7 @@ +services: + php: + build: + context: . + dockerfile: tools/local-env/php-vips/Dockerfile + args: + LOCAL_PHP: ${LOCAL_PHP-latest} diff --git a/src/wp-admin/includes/class-wp-debug-data.php b/src/wp-admin/includes/class-wp-debug-data.php index 76e1cc2c9419f..2339b7bbd0e07 100644 --- a/src/wp-admin/includes/class-wp-debug-data.php +++ b/src/wp-admin/includes/class-wp-debug-data.php @@ -458,6 +458,22 @@ private static function get_wp_server(): array { 'debug' => $imagick_loaded, ); + $ffi_loaded = extension_loaded( 'ffi' ); + + $fields['ffi_availability'] = array( + 'label' => __( 'Is the PHP FFI extension available?' ), + 'value' => ( $ffi_loaded ? __( 'Yes' ) : __( 'No' ) ), + 'debug' => $ffi_loaded, + ); + + $vips_loaded = class_exists( 'Jcupitt\\Vips\\Image' ); + + $fields['vips_availability'] = array( + 'label' => __( 'Is the libvips PHP library available?' ), + 'value' => ( $vips_loaded ? __( 'Yes' ) : __( 'No' ) ), + 'debug' => $vips_loaded, + ); + // Opcode Cache. if ( function_exists( 'opcache_get_status' ) ) { $opcache_status = @opcache_get_status( false ); // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- Warning emitted in failure case. @@ -664,6 +680,20 @@ private static function get_wp_media(): array { 'value' => ( $imagick_version ) ? $imagick_version : __( 'Not available' ), ); + $vips_version = $not_available; + if ( class_exists( 'Jcupitt\\Vips\\Config' ) ) { + try { + $vips_version = Jcupitt\Vips\Config::version(); + } catch ( Exception $e ) { + $vips_version = __( 'Unable to determine' ); + } + } + + $fields['vips_version'] = array( + 'label' => __( 'libvips version' ), + 'value' => $vips_version, + ); + // Get the PHP ini directive values. $file_uploads = ini_get( 'file_uploads' ); $post_max_size = ini_get( 'post_max_size' ); @@ -794,6 +824,31 @@ private static function get_wp_media(): array { ); } + if ( class_exists( 'WP_Image_Editor_Vips' ) ) { + $vips_image_formats = array(); + $vips_formats = array( + 'JPEG' => 'image/jpeg', + 'PNG' => 'image/png', + 'GIF' => 'image/gif', + 'WebP' => 'image/webp', + 'HEIC' => 'image/heic', + 'AVIF' => 'image/avif', + ); + + foreach ( $vips_formats as $vips_label => $vips_mime_type ) { + if ( WP_Image_Editor_Vips::supports_mime_type( $vips_mime_type ) ) { + $vips_image_formats[] = $vips_label; + } + } + + if ( ! empty( $vips_image_formats ) ) { + $fields['vips_formats'] = array( + 'label' => __( 'libvips supported file formats' ), + 'value' => implode( ', ', $vips_image_formats ), + ); + } + } + // Get Ghostscript information, if available. if ( function_exists( 'exec' ) ) { $gs = exec( 'gs --version' ); diff --git a/src/wp-admin/includes/class-wp-site-health.php b/src/wp-admin/includes/class-wp-site-health.php index 31e940b2076e1..2056afaa23670 100644 --- a/src/wp-admin/includes/class-wp-site-health.php +++ b/src/wp-admin/includes/class-wp-site-health.php @@ -1034,6 +1034,13 @@ public function get_test_php_extensions() { ), ); + if ( class_exists( 'Jcupitt\\Vips\\Image' ) ) { + $modules['vips'] = array( + 'class' => 'Jcupitt\\Vips\\Image', + 'required' => false, + ); + } + /** * Filters the array representing all the modules we wish to test for. * diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php new file mode 100644 index 0000000000000..5ad5c3ec72288 --- /dev/null +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -0,0 +1,599 @@ +image ) { + // VIPS uses reference counting and automatic memory management. + $this->image = null; + } + + if ( $this->original_image ) { + $this->original_image = null; + } + } + + /** + * Checks to see if current environment supports VIPS. + * + * @since 6.8.0 + * + * @param array $args + * @return bool + */ + public static function test( $args = array() ) { + // Check if FFI extension is available. + if ( ! extension_loaded( 'ffi' ) ) { + return false; + } + + // Check if the Jcupitt\Vips classes are available via Composer. + if ( ! class_exists( 'Jcupitt\Vips\Config' ) || ! class_exists( 'Jcupitt\Vips\Image' ) ) { + return false; + } + + // Try to get the libvips version to confirm it's working. + try { + $version = Jcupitt\Vips\Config::version(); + if ( empty( $version ) ) { + return false; + } + + // Require libvips 8.7 or later + if ( version_compare( $version, '8.7', '<' ) ) { + return false; + } + } catch ( Exception $e ) { + return false; + } + + return true; + } + + /** + * Checks to see if editor supports the mime-type specified. + * + * @since 6.8.0 + * + * @param string $mime_type + * @return bool + */ + public static function supports_mime_type( $mime_type ) { + $vips_extension = strtoupper( self::get_extension( $mime_type ) ); + + if ( ! $vips_extension ) { + return false; + } + + // Check if VIPS supports this format. + try { + // Map common MIME types to VIPS format names. + $format_map = array( + 'JPEG' => 'jpeg', + 'JPG' => 'jpeg', + 'PNG' => 'png', + 'WEBP' => 'webp', + 'GIF' => 'gif', + 'TIFF' => 'tiff', + 'TIF' => 'tiff', + 'HEIC' => 'heif', + 'AVIF' => 'heif', // AVIF is part of HEIF family. + ); + + $format = isset( $format_map[ $vips_extension ] ) ? $format_map[ $vips_extension ] : strtolower( $vips_extension ); + + // VIPS can usually handle these formats. + $supported_formats = array( 'jpeg', 'png', 'webp', 'gif', 'tiff', 'heif' ); + return in_array( $format, $supported_formats, true ); + } catch ( Exception $e ) { + return false; + } + } + + /** + * Loads image from $this->file into new VIPS Image object. + * + * @since 6.8.0 + * + * @return true|WP_Error True if loaded successfully; WP_Error on failure. + */ + public function load() { + if ( $this->image ) { + return true; + } + + if ( ! is_file( $this->file ) && ! wp_is_stream( $this->file ) ) { + return new WP_Error( 'error_loading_image', __( 'File does not exist?' ), $this->file ); + } + + // VIPS is memory-efficient but still raise the limit. + wp_raise_memory_limit( 'image' ); + + try { + // Load the image. + if ( wp_is_stream( $this->file ) ) { + $file_contents = file_get_contents( $this->file ); + if ( false === $file_contents ) { + return new WP_Error( 'error_loading_image', __( 'File does not exist?' ), $this->file ); + } + $this->image = Jcupitt\Vips\Image::newFromBuffer( $file_contents ); + } else { + $this->image = Jcupitt\Vips\Image::newFromFile( $this->file ); + } + + if ( ! $this->image ) { + return new WP_Error( 'invalid_image', __( 'File is not an image.' ), $this->file ); + } + + // Get image size. + $width = $this->image->width; + $height = $this->image->height; + + if ( ! $width || ! $height ) { + return new WP_Error( 'invalid_image', __( 'Could not read image size.' ), $this->file ); + } + + // Set the mime type. + $size = wp_getimagesize( $this->file ); + if ( $size ) { + $this->mime_type = $size['mime']; + } else { + $this->mime_type = wp_get_image_mime( $this->file ); + } + + if ( ! $this->mime_type ) { + $this->mime_type = $this->default_mime_type; + } + + $this->update_size( $width, $height ); + $this->original_image = $this->image->copy(); + + return $this->set_quality(); + } catch ( Exception $e ) { + return new WP_Error( 'invalid_image', $e->getMessage(), $this->file ); + } + } + + /** + * Sets or updates current image size. + * + * @since 6.8.0 + * + * @param int $width + * @param int $height + * @return true + */ + protected function update_size( $width = false, $height = false ) { + if ( ! $width ) { + $width = $this->image->width; + } + + if ( ! $height ) { + $height = $this->image->height; + } + + return parent::update_size( $width, $height ); + } + + /** + * Resizes current image. + * + * At minimum, either a height or width must be provided. If one of the two is set + * to null, the resize will maintain aspect ratio according to the provided dimension. + * + * @since 6.8.0 + * + * @param int|null $max_w Image width. + * @param int|null $max_h Image height. + * @param bool|array $crop { + * Optional. Image cropping behavior. If false, the image will be scaled (default). + * If true, image will be cropped to the specified dimensions using center positions. + * If an array, the image will be cropped using the array to specify the crop location: + * + * @type string $0 The x crop position. Accepts 'left', 'center', or 'right'. + * @type string $1 The y crop position. Accepts 'top', 'center', or 'bottom'. + * } + * @return true|WP_Error + */ + public function resize( $max_w, $max_h, $crop = false ) { + if ( ( $this->size['width'] === $max_w ) && ( $this->size['height'] === $max_h ) ) { + return true; + } + + $dims = image_resize_dimensions( $this->size['width'], $this->size['height'], $max_w, $max_h, $crop ); + if ( ! $dims ) { + return new WP_Error( 'error_getting_dimensions', __( 'Could not calculate resized image dimensions' ) ); + } + + list( $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h ) = $dims; + + if ( $crop ) { + return $this->crop( $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h ); + } + + try { + // Use resize instead of thumbnail_image for more control. + // Calculate scale factor. + $h_scale = $dst_w / $this->size['width']; + $v_scale = $dst_h / $this->size['height']; + + $this->image = $this->image->resize( $h_scale, array( 'vscale' => $v_scale ) ); + + $this->update_size( $dst_w, $dst_h ); + + return true; + } catch ( Exception $e ) { + return new WP_Error( 'image_resize_error', $e->getMessage() ); + } + } + + /** + * Resize multiple images from a single source. + * + * @since 6.8.0 + * + * @param array $sizes { + * An array of image size arrays. Default sizes are 'small', 'medium', 'large'. + * + * @type array ...$0 { + * @type int $width Image width. + * @type int $height Image height. + * @type bool|array $crop Optional. Whether to crop the image. Default false. + * } + * } + * @return array An array of resized images metadata by size. + */ + public function multi_resize( $sizes ) { + $metadata = array(); + $orig_size = $this->size; + + if ( ! $this->original_image ) { + try { + $this->original_image = $this->image->copy(); + } catch ( Exception $e ) { + return $metadata; + } + } + + foreach ( $sizes as $size => $size_data ) { + try { + $this->image = $this->original_image->copy(); + } catch ( Exception $e ) { + continue; + } + + $this->size = $orig_size; + + if ( ! isset( $size_data['width'] ) && ! isset( $size_data['height'] ) ) { + continue; + } + + if ( ! isset( $size_data['width'] ) ) { + $size_data['width'] = null; + } + + if ( ! isset( $size_data['height'] ) ) { + $size_data['height'] = null; + } + + if ( ! isset( $size_data['crop'] ) ) { + $size_data['crop'] = false; + } + + $resize_result = $this->resize( $size_data['width'], $size_data['height'], $size_data['crop'] ); + $duplicate = ( ( $orig_size['width'] === $size_data['width'] ) && ( $orig_size['height'] === $size_data['height'] ) ); + + if ( ! is_wp_error( $resize_result ) && ! $duplicate ) { + $resized = $this->_save( $this->image ); + + if ( ! is_wp_error( $resized ) && $resized ) { + unset( $resized['path'] ); + $metadata[ $size ] = $resized; + } + } + + } + + // Restore original image and dimensions. + try { + $this->image = $this->original_image->copy(); + $this->size = $orig_size; + } catch ( Exception $e ) { + $this->size = $orig_size; + } + + return $metadata; + } + + /** + * Crops Image. + * + * @since 6.8.0 + * + * @param int $src_x The start x position to crop from. + * @param int $src_y The start y position to crop from. + * @param int $src_w The width to crop. + * @param int $src_h The height to crop. + * @param int|null $dst_w Optional. The destination width. + * @param int|null $dst_h Optional. The destination height. + * @param bool $src_abs Optional. If the destination crop values are absolute. + * @return true|WP_Error + */ + public function crop( $src_x, $src_y, $src_w, $src_h, $dst_w = null, $dst_h = null, $src_abs = false ) { + // If destination width/height isn't specified, use same as source + if ( $dst_w === null ) { + $dst_w = $src_w; + } + + if ( $dst_h === null ) { + $dst_h = $src_h; + } + + try { + // Crop the image. + $cropped = $this->image->crop( (int) $src_x, (int) $src_y, (int) $src_w, (int) $src_h ); + + // Resize if needed. + if ( $src_w !== $dst_w || $src_h !== $dst_h ) { + $h_scale = $dst_w / $src_w; + $v_scale = $dst_h / $src_h; + $cropped = $cropped->resize( $h_scale, array( 'vscale' => $v_scale ) ); + } + + $this->image = $cropped; + $this->update_size( $dst_w, $dst_h ); + + return true; + } catch ( Exception $e ) { + return new WP_Error( 'image_crop_error', $e->getMessage() ); + } + } + + /** + * Rotates current image counter-clockwise by $angle. + * + * @since 6.8.0 + * + * @param float $angle + * @return true|WP_Error + */ + public function rotate( $angle ) { + // VIPS rotate is clockwise, WordPress expects counter-clockwise, + // so we need to invert the angle. + $angle = 360 - $angle; + + try { + $this->image = $this->image->rotate( $angle ); + + // Update size since rotation may change dimensions. + $result = $this->update_size(); + if ( is_wp_error( $result ) ) { + return $result; + } + + return true; + } catch ( Exception $e ) { + return new WP_Error( 'image_rotate_error', $e->getMessage() ); + } + } + + /** + * Flips current image. + * + * @since 6.8.0 + * + * @param bool $horz Flip along Horizontal Axis + * @param bool $vert Flip along Vertical Axis + * @return true|WP_Error + */ + public function flip( $horz, $vert ) { + try { + if ( $horz ) { + $this->image = $this->image->fliphor(); + } + + if ( $vert ) { + $this->image = $this->image->flipver(); + } + + return true; + } catch ( Exception $e ) { + return new WP_Error( 'image_flip_error', $e->getMessage() ); + } + } + + /** + * Saves current image to file. + * + * @since 6.8.0 + * + * @param string $destfilename Optional. Destination filename. Default null. + * @param string $mime_type Optional. The mime-type. Default null. + * @return array|WP_Error { + * Array on success or WP_Error if the file failed to save. + * + * @type string $path Path to the image file. + * @type string $file Name of the image file. + * @type int $width Image width. + * @type int $height Image height. + * @type string $mime-type The mime type of the image. + * @type int $filesize File size of the image. + * } + */ + public function save( $destfilename = null, $mime_type = null ) { + $saved = $this->_save( $this->image, $destfilename, $mime_type ); + + if ( ! is_wp_error( $saved ) ) { + $this->file = $saved['path']; + $this->mime_type = $saved['mime-type']; + } + + return $saved; + } + + /** + * Internal save method. + * + * @since 6.8.0 + * + * @param Jcupitt\Vips\Image $image + * @param string $filename + * @param string $mime_type + * @return array|WP_Error + */ + protected function _save( $image, $filename = null, $mime_type = null ) { + list( $filename, $extension, $mime_type ) = $this->get_output_format( $filename, $mime_type ); + + if ( ! $filename ) { + $filename = $this->generate_filename( null, null, $extension ); + } + + try { + // Prepare save options based on mime type. + $save_options = array(); + + switch ( $mime_type ) { + case 'image/jpeg': + $save_options['Q'] = $this->get_quality(); + $save_options['strip'] = true; + break; + + case 'image/png': + // PNG quality in VIPS is compression level (0-9). + // Convert WP quality (0-100) to VIPS compression (9-0). + $quality = $this->get_quality(); + $compression = 9 - round( ( $quality / 100 ) * 9 ); + $save_options['compression'] = max( 0, min( 9, $compression ) ); + $save_options['strip'] = true; + break; + + case 'image/webp': + $save_options['Q'] = $this->get_quality(); + $save_options['strip'] = true; + break; + + case 'image/gif': + $save_options['strip'] = true; + break; + + case 'image/avif': + $save_options['Q'] = $this->get_quality(); + $save_options['strip'] = true; + break; + } + + if ( wp_is_stream( $filename ) ) { + $buffer = $image->writeToBuffer( '.' . $extension, $save_options ); + if ( false === file_put_contents( $filename, $buffer ) ) { + return new WP_Error( + 'image_save_error', + sprintf( + /* translators: %s: PHP function name. */ + __( '%s failed while writing image to stream.' ), + 'file_put_contents()' + ), + $filename + ); + } + } else { + $dirname = dirname( $filename ); + + if ( ! wp_mkdir_p( $dirname ) ) { + return new WP_Error( + 'image_save_error', + sprintf( + /* translators: %s: Directory path. */ + __( 'Unable to create directory %s. Is its parent directory writable by the server?' ), + esc_html( $dirname ) + ) + ); + } + + $image->writeToFile( $filename, $save_options ); + + // Set correct file permissions. + $stat = stat( $dirname ); + $perms = $stat['mode'] & 0000666; + chmod( $filename, $perms ); + } + + return array( + 'path' => $filename, + 'file' => wp_basename( apply_filters( 'image_make_intermediate_size', $filename ) ), + 'width' => $this->size['width'], + 'height' => $this->size['height'], + 'mime-type' => $mime_type, + 'filesize' => wp_filesize( $filename ), + ); + } catch ( Exception $e ) { + return new WP_Error( 'image_save_error', $e->getMessage(), $filename ); + } + } + + /** + * Streams current image to browser. + * + * @since 6.8.0 + * + * @param string $mime_type Optional. The mime type of the image. Default is the original mime type. + * @return true|WP_Error True on success, WP_Error object on failure. + */ + public function stream( $mime_type = null ) { + list( $filename, $extension, $mime_type ) = $this->get_output_format( null, $mime_type ); + + try { + $save_options = array(); + + switch ( $mime_type ) { + case 'image/png': + $quality = $this->get_quality(); + $compression = 9 - round( ( $quality / 100 ) * 9 ); + $save_options['compression'] = max( 0, min( 9, $compression ) ); + break; + + case 'image/webp': + case 'image/jpeg': + case 'image/avif': + $save_options['Q'] = $this->get_quality(); + break; + } + + // Get the image buffer. + $buffer = $this->image->writeToBuffer( '.' . $extension, $save_options ); + + // Set the appropriate header. + header( "Content-Type: $mime_type" ); + print $buffer; + + return true; + } catch ( Exception $e ) { + return new WP_Error( 'image_stream_error', $e->getMessage() ); + } + } +} diff --git a/src/wp-includes/media.php b/src/wp-includes/media.php index 2ffa92f2edba0..1fa29f79a2503 100644 --- a/src/wp-includes/media.php +++ b/src/wp-includes/media.php @@ -4422,6 +4422,7 @@ function _wp_image_editor_choose( $args = array() ) { require_once ABSPATH . WPINC . '/class-wp-image-editor.php'; require_once ABSPATH . WPINC . '/class-wp-image-editor-gd.php'; require_once ABSPATH . WPINC . '/class-wp-image-editor-imagick.php'; + require_once ABSPATH . WPINC . '/class-wp-image-editor-vips.php'; require_once ABSPATH . WPINC . '/class-avif-info.php'; /** * Filters the list of image editing library classes. @@ -4429,9 +4430,9 @@ function _wp_image_editor_choose( $args = array() ) { * @since 3.5.0 * * @param string[] $image_editors Array of available image editor class names. Defaults are - * 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD'. + * 'WP_Image_Editor_Vips', 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD'. */ - $implementations = apply_filters( 'wp_image_editors', array( 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD' ) ); + $implementations = apply_filters( 'wp_image_editors', array( 'WP_Image_Editor_Vips', 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD' ) ); $editors = wp_cache_get( 'wp_image_editor_choose', 'image_editor' ); diff --git a/src/wp-includes/update.php b/src/wp-includes/update.php index 9f4257ab03da6..0543db369eac9 100644 --- a/src/wp-includes/update.php +++ b/src/wp-includes/update.php @@ -180,6 +180,22 @@ function ( $carry, $prefixed_myisam_table ) use ( $all_unprefixed_tables ) { ); } + if ( extension_loaded( 'ffi' ) && class_exists( 'Jcupitt\\Vips\\Config' ) && class_exists( 'Jcupitt\\Vips\\Image' ) ) { + require_once ABSPATH . WPINC . '/class-wp-image-editor-vips.php'; + + // Add data for libvips WebP, AVIF, HEIC and JPEG XL support. + $query['image_support']['vips'] = array_keys( + array_filter( + array( + 'webp' => WP_Image_Editor_Vips::supports_mime_type( 'image/webp' ), + 'avif' => WP_Image_Editor_Vips::supports_mime_type( 'image/avif' ), + 'heic' => WP_Image_Editor_Vips::supports_mime_type( 'image/heic' ), + 'jxl' => false, + ) + ) + ); + } + /** * Filters the query arguments sent as part of the core version check. * @@ -203,7 +219,7 @@ function ( $carry, $prefixed_myisam_table ) use ( $all_unprefixed_tables ) { * @type int $initial_db_version Database version of WordPress at time of installation. * @type array $extensions List of PHP extensions and their versions. * @type array $platform_flags List containing the operating system name and bit support. - * @type array $image_support List of image formats supported by GD and Imagick. + * @type array $image_support List of image formats supported by GD, Imagick, and VIPS. * } */ $query = apply_filters( 'core_version_check_query_args', $query ); diff --git a/tests/phpunit/tests/image/editorVips.php b/tests/phpunit/tests/image/editorVips.php new file mode 100644 index 0000000000000..af77235831768 --- /dev/null +++ b/tests/phpunit/tests/image/editorVips.php @@ -0,0 +1,224 @@ +remove_added_uploads(); + + parent::tear_down(); + } + + /** + * Tests support for commonly used mime types. + */ + public function test_supports_mime_type() { + $vips_image_editor = new WP_Image_Editor_Vips( null ); + + $this->assertTrue( $vips_image_editor->supports_mime_type( 'image/jpeg' ), 'Does not support image/jpeg' ); + $this->assertTrue( $vips_image_editor->supports_mime_type( 'image/png' ), 'Does not support image/png' ); + $this->assertTrue( $vips_image_editor->supports_mime_type( 'image/gif' ), 'Does not support image/gif' ); + } + + /** + * Tests resizing an image without cropping. + */ + public function test_resize() { + $file = DIR_TESTDATA . '/images/waffles.jpg'; + + $vips_image_editor = new WP_Image_Editor_Vips( $file ); + $vips_image_editor->load(); + + $vips_image_editor->resize( 100, 50 ); + + $this->assertSame( + array( + 'width' => 75, + 'height' => 50, + ), + $vips_image_editor->get_size() + ); + } + + /** + * Tests multi_resize() with a single generated sub-size. + */ + public function test_single_multi_resize() { + $file = DIR_TESTDATA . '/images/waffles.jpg'; + + $vips_image_editor = new WP_Image_Editor_Vips( $file ); + $vips_image_editor->load(); + + $sizes_array = array( + array( + 'width' => 50, + 'height' => 50, + ), + ); + + $resized = $vips_image_editor->multi_resize( $sizes_array ); + + $expected_array = array( + array( + 'file' => 'waffles-50x33.jpg', + 'width' => 50, + 'height' => 33, + 'mime-type' => 'image/jpeg', + 'filesize' => wp_filesize( dirname( $file ) . '/waffles-50x33.jpg' ), + ), + ); + + $this->assertSame( $expected_array, $resized ); + + $image_path = DIR_TESTDATA . '/images/' . $resized[0]['file']; + $this->assertImageDimensions( + $image_path, + $expected_array[0]['width'], + $expected_array[0]['height'] + ); + } + + /** + * Tests that multi_resize() does not create an image when dimensions are missing. + * + * @ticket 26823 + */ + public function test_multi_resize_does_not_create() { + $file = DIR_TESTDATA . '/images/waffles.jpg'; + + $vips_image_editor = new WP_Image_Editor_Vips( $file ); + $vips_image_editor->load(); + + $sizes_array = array( + array( + 'width' => 0, + 'height' => 0, + ), + array( + 'width' => null, + 'height' => null, + ), + array( + 'width' => 0, + ), + array( + 'height' => 0, + ), + ); + + $resized = $vips_image_editor->multi_resize( $sizes_array ); + + $this->assertEmpty( $resized ); + } + + /** + * Tests resizing with crop enabled. + */ + public function test_resize_and_crop() { + $file = DIR_TESTDATA . '/images/waffles.jpg'; + + $vips_image_editor = new WP_Image_Editor_Vips( $file ); + $vips_image_editor->load(); + + $vips_image_editor->resize( 100, 50, true ); + + $this->assertSame( + array( + 'width' => 100, + 'height' => 50, + ), + $vips_image_editor->get_size() + ); + } + + /** + * Tests basic crop behavior. + */ + public function test_crop() { + $file = DIR_TESTDATA . '/images/gradient-square.jpg'; + + $vips_image_editor = new WP_Image_Editor_Vips( $file ); + $vips_image_editor->load(); + + $vips_image_editor->crop( 0, 0, 50, 50 ); + + $this->assertSame( + array( + 'width' => 50, + 'height' => 50, + ), + $vips_image_editor->get_size() + ); + } + + /** + * Tests rotation behavior. + */ + public function test_rotate() { + $file = DIR_TESTDATA . '/images/gradient-square.jpg'; + + $vips_image_editor = new WP_Image_Editor_Vips( $file ); + $vips_image_editor->load(); + + $result = $vips_image_editor->rotate( 180 ); + + $this->assertTrue( $result ); + $this->assertSame( + array( + 'width' => 100, + 'height' => 100, + ), + $vips_image_editor->get_size() + ); + } + + /** + * Tests horizontal flip behavior. + */ + public function test_flip() { + $file = DIR_TESTDATA . '/images/gradient-square.jpg'; + + $vips_image_editor = new WP_Image_Editor_Vips( $file ); + $vips_image_editor->load(); + + $result = $vips_image_editor->flip( true, false ); + + $this->assertTrue( $result ); + $this->assertSame( + array( + 'width' => 100, + 'height' => 100, + ), + $vips_image_editor->get_size() + ); + } +} diff --git a/tests/phpunit/tests/image/functions.php b/tests/phpunit/tests/image/functions.php index 7b1e652eb4b68..a929246b1dbba 100644 --- a/tests/phpunit/tests/image/functions.php +++ b/tests/phpunit/tests/image/functions.php @@ -18,6 +18,7 @@ public function set_up() { require_once ABSPATH . WPINC . '/class-wp-image-editor.php'; require_once ABSPATH . WPINC . '/class-wp-image-editor-gd.php'; require_once ABSPATH . WPINC . '/class-wp-image-editor-imagick.php'; + require_once ABSPATH . WPINC . '/class-wp-image-editor-vips.php'; require_once DIR_TESTDATA . '/../includes/mock-image-editor.php'; @@ -36,7 +37,7 @@ public function set_up() { * @return string[] Available image editor classes; empty array when none are available. */ private function get_image_editor_engine_classes() { - $classes = array( 'WP_Image_Editor_GD', 'WP_Image_Editor_Imagick' ); + $classes = array( 'WP_Image_Editor_GD', 'WP_Image_Editor_Imagick', 'WP_Image_Editor_Vips' ); foreach ( $classes as $key => $class ) { if ( ! call_user_func( array( $class, 'test' ) ) ) { diff --git a/tests/phpunit/tests/image/resizeVips.php b/tests/phpunit/tests/image/resizeVips.php new file mode 100644 index 0000000000000..4974b1992e2de --- /dev/null +++ b/tests/phpunit/tests/image/resizeVips.php @@ -0,0 +1,27 @@ + /usr/local/etc/php/conf.d/vips-ffi.ini diff --git a/tools/local-env/scripts/utils.js b/tools/local-env/scripts/utils.js index 58c02716241d5..f2b607efe2d2f 100644 --- a/tools/local-env/scripts/utils.js +++ b/tools/local-env/scripts/utils.js @@ -90,6 +90,11 @@ const local_env_utils = { */ get_compose_files: function() { const composeFiles = [ 'docker-compose.yml' ]; + const shouldUseVips = process.env.LOCAL_PHP_VIPS === 'true'; + + if ( shouldUseVips && existsSync( 'docker-compose.vips.yml' ) ) { + composeFiles.push( 'docker-compose.vips.yml' ); + } if ( existsSync( 'docker-compose.override.yml' ) ) { composeFiles.push( 'docker-compose.override.yml' ); From dca1845c1cd769740ec2f61a60cd12d5f7149b33 Mon Sep 17 00:00:00 2001 From: Nick Chomey Date: Sun, 15 Feb 2026 11:09:31 -0600 Subject: [PATCH 02/84] Refine VIPS capability detection and clean debug-data loading --- .../class-wp-image-editor-vips.php | 40 ++++++++++--------- 1 file changed, 22 insertions(+), 18 deletions(-) diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index 5ad5c3ec72288..6651c2c5e78a0 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -91,26 +91,30 @@ public static function supports_mime_type( $mime_type ) { return false; } - // Check if VIPS supports this format. - try { - // Map common MIME types to VIPS format names. - $format_map = array( - 'JPEG' => 'jpeg', - 'JPG' => 'jpeg', - 'PNG' => 'png', - 'WEBP' => 'webp', - 'GIF' => 'gif', - 'TIFF' => 'tiff', - 'TIF' => 'tiff', - 'HEIC' => 'heif', - 'AVIF' => 'heif', // AVIF is part of HEIF family. - ); + if ( ! self::test() ) { + return false; + } - $format = isset( $format_map[ $vips_extension ] ) ? $format_map[ $vips_extension ] : strtolower( $vips_extension ); + $extension_map = array( + 'JPEG' => 'jpg', + 'JPG' => 'jpg', + 'PNG' => 'png', + 'WEBP' => 'webp', + 'GIF' => 'gif', + 'TIFF' => 'tif', + 'TIF' => 'tif', + 'HEIC' => 'heic', + 'AVIF' => 'avif', + ); + + $target_extension = isset( $extension_map[ $vips_extension ] ) ? $extension_map[ $vips_extension ] : strtolower( $vips_extension ); + + // Probe encoder support directly. + try { + $test_image = Jcupitt\Vips\Image::black( 1, 1 ); + $buffer = $test_image->writeToBuffer( '.' . $target_extension ); - // VIPS can usually handle these formats. - $supported_formats = array( 'jpeg', 'png', 'webp', 'gif', 'tiff', 'heif' ); - return in_array( $format, $supported_formats, true ); + return is_string( $buffer ) && '' !== $buffer; } catch ( Exception $e ) { return false; } From 84784a5c14763288823072007b9b2ee00e71a767 Mon Sep 17 00:00:00 2001 From: Nick Chomey Date: Sun, 15 Feb 2026 12:15:44 -0600 Subject: [PATCH 03/84] Expand VIPS parity with GD/Imagick behavior and tests --- .../class-wp-image-editor-vips.php | 36 +- tests/phpunit/tests/image/editorVips.php | 401 +++++++++++++++++- 2 files changed, 417 insertions(+), 20 deletions(-) diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index 6651c2c5e78a0..0d7561929d55c 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -350,15 +350,26 @@ public function multi_resize( $sizes ) { * @return true|WP_Error */ public function crop( $src_x, $src_y, $src_w, $src_h, $dst_w = null, $dst_h = null, $src_abs = false ) { - // If destination width/height isn't specified, use same as source - if ( $dst_w === null ) { + // If destination width/height isn't specified, use same as source. + if ( ! $dst_w ) { $dst_w = $src_w; } - if ( $dst_h === null ) { + if ( ! $dst_h ) { $dst_h = $src_h; } + foreach ( array( $src_w, $src_h, $dst_w, $dst_h ) as $value ) { + if ( ! is_numeric( $value ) || (int) $value <= 0 ) { + return new WP_Error( 'image_crop_error', __( 'Image crop failed.' ), $this->file ); + } + } + + if ( $src_abs ) { + $src_w -= $src_x; + $src_h -= $src_y; + } + try { // Crop the image. $cropped = $this->image->crop( (int) $src_x, (int) $src_y, (int) $src_w, (int) $src_h ); @@ -388,12 +399,19 @@ public function crop( $src_x, $src_y, $src_w, $src_h, $dst_w = null, $dst_h = nu * @return true|WP_Error */ public function rotate( $angle ) { - // VIPS rotate is clockwise, WordPress expects counter-clockwise, - // so we need to invert the angle. - $angle = 360 - $angle; + $angle = -$angle; + $angle = ( 360 + ( $angle % 360 ) ) % 360; try { - $this->image = $this->image->rotate( $angle ); + if ( 90 === $angle ) { + $this->image = $this->image->rot90(); + } elseif ( 180 === $angle ) { + $this->image = $this->image->rot180(); + } elseif ( 270 === $angle ) { + $this->image = $this->image->rot270(); + } else { + $this->image = $this->image->rotate( $angle ); + } // Update size since rotation may change dimensions. $result = $this->update_size(); @@ -418,11 +436,11 @@ public function rotate( $angle ) { */ public function flip( $horz, $vert ) { try { - if ( $horz ) { + if ( $vert ) { $this->image = $this->image->fliphor(); } - if ( $vert ) { + if ( $horz ) { $this->image = $this->image->flipver(); } diff --git a/tests/phpunit/tests/image/editorVips.php b/tests/phpunit/tests/image/editorVips.php index af77235831768..a5f989a75f6b3 100644 --- a/tests/phpunit/tests/image/editorVips.php +++ b/tests/phpunit/tests/image/editorVips.php @@ -19,6 +19,7 @@ class Tests_Image_Editor_Vips extends WP_Image_UnitTestCase { public function set_up() { require_once ABSPATH . WPINC . '/class-wp-image-editor.php'; require_once ABSPATH . WPINC . '/class-wp-image-editor-vips.php'; + require_once DIR_TESTROOT . '/includes/class-wp-test-stream.php'; parent::set_up(); } @@ -123,13 +124,50 @@ public function test_multi_resize_does_not_create() { 'width' => 0, 'height' => 0, ), + array( + 'width' => 0, + 'height' => 0, + 'crop' => true, + ), + array( + 'width' => null, + 'height' => null, + ), array( 'width' => null, 'height' => null, + 'crop' => true, + ), + array( + 'width' => '', + 'height' => '', + ), + array( + 'width' => '', + 'height' => '', + 'crop' => true, ), array( 'width' => 0, ), + array( + 'width' => 0, + 'crop' => true, + ), + array( + 'width' => null, + ), + array( + 'width' => null, + 'crop' => true, + ), + array( + 'width' => '', + ), + array( + 'width' => '', + 'crop' => true, + ), array( 'height' => 0, ), @@ -140,6 +178,151 @@ public function test_multi_resize_does_not_create() { $this->assertEmpty( $resized ); } + /** + * Tests multi_resize() with multiple sizes. + * + * @ticket 26823 + */ + public function test_multi_resize() { + $file = DIR_TESTDATA . '/images/waffles.jpg'; + + $vips_image_editor = new WP_Image_Editor_Vips( $file ); + $vips_image_editor->load(); + + $sizes_array = array( + array( + 'width' => 10, + 'height' => 10, + 'crop' => false, + ), + array( + 'width' => 75, + 'height' => 50, + 'crop' => true, + ), + array( + 'width' => 9999, + 'height' => 20, + 'crop' => false, + ), + array( + 'width' => 45, + 'height' => 9999, + 'crop' => true, + ), + array( + 'width' => 50, + ), + array( + 'width' => 55, + 'height' => null, + ), + array( + 'height' => 55, + ), + array( + 'width' => null, + 'height' => 60, + ), + array( + 'width' => -9999, + 'height' => 70, + ), + array( + 'width' => 200, + 'height' => -9999, + ), + ); + + $resized = $vips_image_editor->multi_resize( $sizes_array ); + + $expected_array = array( + array( + 'file' => 'waffles-10x7.jpg', + 'width' => 10, + 'height' => 7, + 'mime-type' => 'image/jpeg', + 'filesize' => wp_filesize( dirname( $file ) . '/waffles-10x7.jpg' ), + ), + array( + 'file' => 'waffles-75x50.jpg', + 'width' => 75, + 'height' => 50, + 'mime-type' => 'image/jpeg', + 'filesize' => wp_filesize( dirname( $file ) . '/waffles-75x50.jpg' ), + ), + array( + 'file' => 'waffles-30x20.jpg', + 'width' => 30, + 'height' => 20, + 'mime-type' => 'image/jpeg', + 'filesize' => wp_filesize( dirname( $file ) . '/waffles-30x20.jpg' ), + ), + array( + 'file' => 'waffles-45x400.jpg', + 'width' => 45, + 'height' => 400, + 'mime-type' => 'image/jpeg', + 'filesize' => wp_filesize( dirname( $file ) . '/waffles-45x400.jpg' ), + ), + array( + 'file' => 'waffles-50x33.jpg', + 'width' => 50, + 'height' => 33, + 'mime-type' => 'image/jpeg', + 'filesize' => wp_filesize( dirname( $file ) . '/waffles-50x33.jpg' ), + ), + array( + 'file' => 'waffles-55x37.jpg', + 'width' => 55, + 'height' => 37, + 'mime-type' => 'image/jpeg', + 'filesize' => wp_filesize( dirname( $file ) . '/waffles-55x37.jpg' ), + ), + array( + 'file' => 'waffles-83x55.jpg', + 'width' => 83, + 'height' => 55, + 'mime-type' => 'image/jpeg', + 'filesize' => wp_filesize( dirname( $file ) . '/waffles-83x55.jpg' ), + ), + array( + 'file' => 'waffles-90x60.jpg', + 'width' => 90, + 'height' => 60, + 'mime-type' => 'image/jpeg', + 'filesize' => wp_filesize( dirname( $file ) . '/waffles-90x60.jpg' ), + ), + array( + 'file' => 'waffles-105x70.jpg', + 'width' => 105, + 'height' => 70, + 'mime-type' => 'image/jpeg', + 'filesize' => wp_filesize( dirname( $file ) . '/waffles-105x70.jpg' ), + ), + array( + 'file' => 'waffles-200x133.jpg', + 'width' => 200, + 'height' => 133, + 'mime-type' => 'image/jpeg', + 'filesize' => wp_filesize( dirname( $file ) . '/waffles-200x133.jpg' ), + ), + ); + + $this->assertNotNull( $resized ); + $this->assertSame( $expected_array, $resized ); + + foreach ( $resized as $key => $image_data ) { + $image_path = DIR_TESTDATA . '/images/' . $image_data['file']; + + $this->assertImageDimensions( + $image_path, + $expected_array[ $key ]['width'], + $expected_array[ $key ]['height'] + ); + } + } + /** * Tests resizing with crop enabled. */ @@ -161,25 +344,138 @@ public function test_resize_and_crop() { } /** - * Tests basic crop behavior. + * Tests crop behavior. + * + * @ticket 51937 + * + * @dataProvider data_crop */ - public function test_crop() { + public function test_crop( $src_x, $src_y, $src_w, $src_h, $dst_w = null, $dst_h = null, $src_abs = false ) { $file = DIR_TESTDATA . '/images/gradient-square.jpg'; $vips_image_editor = new WP_Image_Editor_Vips( $file ); $vips_image_editor->load(); - $vips_image_editor->crop( 0, 0, 50, 50 ); + $vips_image_editor->crop( $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h, $src_abs ); $this->assertSame( array( - 'width' => 50, - 'height' => 50, + 'width' => (int) $src_w, + 'height' => (int) $src_h, ), $vips_image_editor->get_size() ); } + /** + * Data provider for valid crop dimensions. + * + * @return array + */ + public function data_crop() { + return array( + 'src dimensions as ints' => array( + 'src_x' => 0, + 'src_y' => 0, + 'src_w' => 50, + 'src_h' => 50, + ), + 'src dimensions as numeric strings' => array( + 'src_x' => 10, + 'src_y' => '10', + 'src_w' => '50', + 'src_h' => '50', + ), + 'dst dimensions as ints' => array( + 'src_x' => 10, + 'src_y' => 10, + 'src_w' => 150, + 'src_h' => 150, + 'dst_w' => 150, + 'dst_h' => 150, + ), + 'dst dimensions as numeric strings' => array( + 'src_x' => 10, + 'src_y' => '10', + 'src_w' => 150, + 'src_h' => 150, + 'dst_w' => '150', + 'dst_h' => '150', + ), + ); + } + + /** + * Tests that crop() returns WP_Error for invalid dimensions. + * + * @ticket 51937 + * + * @dataProvider data_crop_invalid_dimensions + */ + public function test_crop_invalid_dimensions( $src_x, $src_y, $src_w, $src_h, $dst_w = null, $dst_h = null, $src_abs = false ) { + $file = DIR_TESTDATA . '/images/gradient-square.jpg'; + + $vips_image_editor = new WP_Image_Editor_Vips( $file ); + $vips_image_editor->load(); + + $actual = $vips_image_editor->crop( $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h, $src_abs ); + + $this->assertInstanceOf( 'WP_Error', $actual ); + $this->assertSame( 'image_crop_error', $actual->get_error_code() ); + } + + /** + * Data provider for invalid crop dimensions. + * + * @return array + */ + public function data_crop_invalid_dimensions() { + return array( + 'src height must be greater than 0' => array( + 'src_x' => 0, + 'src_y' => 0, + 'src_w' => 100, + 'src_h' => 0, + ), + 'src width must be greater than 0' => array( + 'src_x' => 10, + 'src_y' => 10, + 'src_w' => 0, + 'src_h' => 100, + ), + 'src height must be numeric and greater than 0' => array( + 'src_x' => 10, + 'src_y' => 10, + 'src_w' => 100, + 'src_h' => 'NaN', + ), + 'dst height must be numeric and greater than 0' => array( + 'src_x' => 0, + 'src_y' => 0, + 'src_w' => 100, + 'src_h' => 50, + 'dst_w' => '100', + 'dst_h' => 'NaN', + ), + 'src and dst dimensions must be greater than 0' => array( + 'src_x' => 0, + 'src_y' => 0, + 'src_w' => 0, + 'src_h' => 0, + 'dst_w' => 0, + 'dst_h' => 0, + ), + 'src and dst dimensions as strings must be greater than 0' => array( + 'src_x' => 0, + 'src_y' => 0, + 'src_w' => '0', + 'src_h' => '0', + 'dst_w' => '0', + 'dst_h' => '0', + ), + ); + } + /** * Tests rotation behavior. */ @@ -205,20 +501,103 @@ public function test_rotate() { * Tests horizontal flip behavior. */ public function test_flip() { - $file = DIR_TESTDATA . '/images/gradient-square.jpg'; + $file = DIR_TESTDATA . '/images/one-blue-pixel-100x100.png'; $vips_image_editor = new WP_Image_Editor_Vips( $file ); $vips_image_editor->load(); + $save_to_file = tempnam( get_temp_dir(), '' ) . '.png'; + $result = $vips_image_editor->flip( true, false ); + $vips_image_editor->save( $save_to_file ); $this->assertTrue( $result ); - $this->assertSame( - array( - 'width' => 100, - 'height' => 100, + + $verify = new WP_Image_Editor_Vips( $save_to_file ); + $verify->load(); + $property = new ReflectionProperty( $verify, 'image' ); + + if ( PHP_VERSION_ID < 80100 ) { + $property->setAccessible( true ); + } + + $image = $property->getValue( $verify ); + if ( ! is_callable( array( $image, 'getpoint' ) ) ) { + unlink( $save_to_file ); + $this->markTestSkipped( 'The image editor does not support getpoint().' ); + } + + $pixel = $image->getpoint( 0, 99 ); + $this->assertSame( 255, (int) $pixel[2] ); + + unlink( $save_to_file ); + } + + /** + * Tests that WP_Image_Editor_Vips handles extensionless images. + * + * @ticket 39195 + */ + public function test_image_non_existent_extension() { + $vips_image_editor = new WP_Image_Editor_Vips( DIR_TESTDATA . '/images/test-image-no-extension' ); + + $loaded = $vips_image_editor->load(); + + $this->assertTrue( $loaded ); + } + + /** + * Tests that images can be loaded and written over streams. + */ + public function test_streams() { + stream_wrapper_register( 'wptest', 'WP_Test_Stream' ); + WP_Test_Stream::$data = array( + 'Tests_Image_Editor_Vips' => array( + '/read.jpg' => file_get_contents( DIR_TESTDATA . '/images/waffles.jpg' ), ), - $vips_image_editor->get_size() ); + + $file = 'wptest://Tests_Image_Editor_Vips/read.jpg'; + $vips_image_editor = new WP_Image_Editor_Vips( $file ); + + $loaded = $vips_image_editor->load(); + $this->assertNotWPError( $loaded ); + + $temp_file = 'wptest://Tests_Image_Editor_Vips/write.jpg'; + $saved = $vips_image_editor->save( $temp_file ); + + if ( $temp_file !== $saved['path'] ) { + unlink( $saved['path'] ); + } + + unlink( $temp_file ); + + $this->assertNotWPError( $saved ); + $this->assertSame( $temp_file, $saved['path'] ); + } + + /** + * @ticket 51665 + */ + public function test_directory_creation() { + $file = realpath( DIR_TESTDATA ) . '/images/a2-small.jpg'; + $directory = realpath( DIR_TESTDATA ) . '/images/nonexistent-directory'; + + $vips_image_editor = new WP_Image_Editor_Vips( $file ); + + $this->assertFileDoesNotExist( $directory ); + + $loaded = $vips_image_editor->load(); + $this->assertNotWPError( $loaded ); + + $resized = $vips_image_editor->resize( 100, 100, true ); + $this->assertNotWPError( $resized ); + + $saved = $vips_image_editor->save( $directory . '/a2-small-cropped.jpg' ); + + unlink( $directory . '/a2-small-cropped.jpg' ); + rmdir( $directory ); + + $this->assertNotWPError( $saved ); } } From 4ae8f52e345b95f6ca93fae799d19c3955198fc6 Mon Sep 17 00:00:00 2001 From: Nick Chomey Date: Sun, 15 Feb 2026 12:25:16 -0600 Subject: [PATCH 04/84] Incorporate beneficial MIME support improvements from VIPS fork --- .../class-wp-image-editor-vips.php | 65 ++++++++++++++++--- 1 file changed, 57 insertions(+), 8 deletions(-) diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index 0d7561929d55c..0202f426c8c81 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -28,6 +28,16 @@ class WP_Image_Editor_Vips extends WP_Image_Editor { */ protected $original_image; + /** + * Cache of mime type support checks. + * + * Dynamic writeToBuffer probe is used because VIPS support depends on runtime configuration + * and optional dependencies. Cache prevents repeated expensive encoder checks. + * + * @var array + */ + protected static $mime_support_cache = array(); + public function __destruct() { if ( $this->image ) { // VIPS uses reference counting and automatic memory management. @@ -85,13 +95,21 @@ public static function test( $args = array() ) { * @return bool */ public static function supports_mime_type( $mime_type ) { + if ( isset( self::$mime_support_cache[ $mime_type ] ) ) { + return self::$mime_support_cache[ $mime_type ]; + } + $vips_extension = strtoupper( self::get_extension( $mime_type ) ); if ( ! $vips_extension ) { + self::$mime_support_cache[ $mime_type ] = false; + return false; } if ( ! self::test() ) { + self::$mime_support_cache[ $mime_type ] = false; + return false; } @@ -104,18 +122,41 @@ public static function supports_mime_type( $mime_type ) { 'TIFF' => 'tif', 'TIF' => 'tif', 'HEIC' => 'heic', + 'HEIF' => 'heif', 'AVIF' => 'avif', + 'JXL' => 'jxl', ); $target_extension = isset( $extension_map[ $vips_extension ] ) ? $extension_map[ $vips_extension ] : strtolower( $vips_extension ); // Probe encoder support directly. + // Use Image::black() to test write support (encoding) rather than findLoad() which only tests read support (decoding). try { $test_image = Jcupitt\Vips\Image::black( 1, 1 ); - $buffer = $test_image->writeToBuffer( '.' . $target_extension ); + + // Some formats (like GIF) have issues with writeToBuffer in ImageMagick, so test with writeToFile + $temp_file = tempnam( sys_get_temp_dir(), 'vips_test_' ) . '.' . $target_extension; + + try { + $test_image->writeToFile( $temp_file ); + $supported = file_exists( $temp_file ) && filesize( $temp_file ) > 0; + + if ( file_exists( $temp_file ) ) { + unlink( $temp_file ); + } + } catch ( Exception $write_error ) { + $supported = false; + if ( file_exists( $temp_file ) ) { + unlink( $temp_file ); + } + } + + self::$mime_support_cache[ $mime_type ] = $supported; - return is_string( $buffer ) && '' !== $buffer; + return $supported; } catch ( Exception $e ) { + self::$mime_support_cache[ $mime_type ] = false; + return false; } } @@ -359,6 +400,7 @@ public function crop( $src_x, $src_y, $src_w, $src_h, $dst_w = null, $dst_h = nu $dst_h = $src_h; } + // Validate all dimension parameters match GD pattern for consistency. foreach ( array( $src_w, $src_h, $dst_w, $dst_h ) as $value ) { if ( ! is_numeric( $value ) || (int) $value <= 0 ) { return new WP_Error( 'image_crop_error', __( 'Image crop failed.' ), $this->file ); @@ -371,13 +413,17 @@ public function crop( $src_x, $src_y, $src_w, $src_h, $dst_w = null, $dst_h = nu } try { - // Crop the image. - $cropped = $this->image->crop( (int) $src_x, (int) $src_y, (int) $src_w, (int) $src_h ); + // Clamp crop dimensions to image bounds (matching GD behavior). + $actual_src_w = min( (int) $src_w, $this->image->width - (int) $src_x ); + $actual_src_h = min( (int) $src_h, $this->image->height - (int) $src_y ); + + // Crop the image with clamped dimensions. + $cropped = $this->image->crop( (int) $src_x, (int) $src_y, $actual_src_w, $actual_src_h ); - // Resize if needed. - if ( $src_w !== $dst_w || $src_h !== $dst_h ) { - $h_scale = $dst_w / $src_w; - $v_scale = $dst_h / $src_h; + // Resize to destination dimensions (GD resamples to $dst_w x $dst_h regardless of actual cropped size). + if ( $actual_src_w !== $dst_w || $actual_src_h !== $dst_h ) { + $h_scale = $dst_w / $actual_src_w; + $v_scale = $dst_h / $actual_src_h; $cropped = $cropped->resize( $h_scale, array( 'vscale' => $v_scale ) ); } @@ -403,6 +449,7 @@ public function rotate( $angle ) { $angle = ( 360 + ( $angle % 360 ) ) % 360; try { + // Use fast rot90/rot180/rot270 paths for right angles to avoid interpolation and improve speed. if ( 90 === $angle ) { $this->image = $this->image->rot90(); } elseif ( 180 === $angle ) { @@ -436,6 +483,8 @@ public function rotate( $angle ) { */ public function flip( $horz, $vert ) { try { + // WordPress flip convention: $vert=flip vertically (use fliphor to flip along horizontal axis). + // WordPress flip convention: $horz=flip horizontally (use flipver to flip along vertical axis). if ( $vert ) { $this->image = $this->image->fliphor(); } From 0f101fe8ee7a68aa3c83795c9c4716f915765914 Mon Sep 17 00:00:00 2001 From: Nick Chomey Date: Sun, 15 Feb 2026 19:24:52 -0600 Subject: [PATCH 05/84] Fix stream wrapper registration to check if already registered --- tests/phpunit/tests/image/editorVips.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/phpunit/tests/image/editorVips.php b/tests/phpunit/tests/image/editorVips.php index a5f989a75f6b3..dbff654ce3e56 100644 --- a/tests/phpunit/tests/image/editorVips.php +++ b/tests/phpunit/tests/image/editorVips.php @@ -550,7 +550,9 @@ public function test_image_non_existent_extension() { * Tests that images can be loaded and written over streams. */ public function test_streams() { - stream_wrapper_register( 'wptest', 'WP_Test_Stream' ); + if ( ! in_array( 'wptest', stream_get_wrappers(), true ) ) { + stream_wrapper_register( 'wptest', 'WP_Test_Stream' ); + } WP_Test_Stream::$data = array( 'Tests_Image_Editor_Vips' => array( '/read.jpg' => file_get_contents( DIR_TESTDATA . '/images/waffles.jpg' ), From 701d20acbbd10b1dd31ba01b4e2429e92747643e Mon Sep 17 00:00:00 2001 From: Nick Chomey Date: Sun, 15 Feb 2026 19:26:46 -0600 Subject: [PATCH 06/84] Add alpha preservation tests and remove test_directory_creation (Imagick-specific test) --- tests/phpunit/tests/image/editorVips.php | 200 ++++++++++++++++++----- 1 file changed, 155 insertions(+), 45 deletions(-) diff --git a/tests/phpunit/tests/image/editorVips.php b/tests/phpunit/tests/image/editorVips.php index dbff654ce3e56..a64efe94f42ad 100644 --- a/tests/phpunit/tests/image/editorVips.php +++ b/tests/phpunit/tests/image/editorVips.php @@ -88,6 +88,7 @@ public function test_single_multi_resize() { $resized = $vips_image_editor->multi_resize( $sizes_array ); + // First, check to see if returned array is as expected. $expected_array = array( array( 'file' => 'waffles-50x33.jpg', @@ -100,6 +101,7 @@ public function test_single_multi_resize() { $this->assertSame( $expected_array, $resized ); + // Now, verify real dimensions are as expected. $image_path = DIR_TESTDATA . '/images/' . $resized[0]['file']; $this->assertImageDimensions( $image_path, @@ -175,6 +177,7 @@ public function test_multi_resize_does_not_create() { $resized = $vips_image_editor->multi_resize( $sizes_array ); + // If no images are generated, the returned array is empty. $this->assertEmpty( $resized ); } @@ -190,53 +193,105 @@ public function test_multi_resize() { $vips_image_editor->load(); $sizes_array = array( + + /* + * #0 - 10x10 resize, no cropping. + * By aspect, should be 10x6 output. + */ array( 'width' => 10, 'height' => 10, 'crop' => false, ), + + /* + * #1 - 75x50 resize, with cropping. + * Output dimensions should be 75x50 + */ array( 'width' => 75, 'height' => 50, 'crop' => true, ), + + /* + * #2 - 20 pixel max height, no cropping. + * By aspect, should be 30x20 output. + */ array( - 'width' => 9999, + 'width' => 9999, // Arbitrary high value. 'height' => 20, 'crop' => false, ), + + /* + * #3 - 45 pixel max height, with cropping. + * By aspect, should be 45x400 output. + */ array( 'width' => 45, - 'height' => 9999, + 'height' => 9999, // Arbitrary high value. 'crop' => true, ), + + /* + * #4 - 50 pixel max width, no cropping. + * By aspect, should be 50x33 output. + */ array( 'width' => 50, ), + + /* + * #5 - 55 pixel max width, no cropping, null height + * By aspect, should be 55x36 output. + */ array( 'width' => 55, 'height' => null, ), + + /* + * #6 - 55 pixel max height, no cropping, no width specified. + * By aspect, should be 82x55 output. + */ array( 'height' => 55, ), + + /* + * #7 - 60 pixel max height, no cropping, null width. + * By aspect, should be 90x60 output. + */ array( 'width' => null, 'height' => 60, ), + + /* + * #8 - 70 pixel max height, no cropping, negative width. + * By aspect, should be 105x70 output. + */ array( - 'width' => -9999, + 'width' => -9999, // Arbitrary negative value. 'height' => 70, ), + + /* + * #9 - 200 pixel max width, no cropping, negative height. + * By aspect, should be 200x133 output. + */ array( 'width' => 200, - 'height' => -9999, + 'height' => -9999, // Arbitrary negative value. ), ); $resized = $vips_image_editor->multi_resize( $sizes_array ); $expected_array = array( + + // #0 array( 'file' => 'waffles-10x7.jpg', 'width' => 10, @@ -244,6 +299,8 @@ public function test_multi_resize() { 'mime-type' => 'image/jpeg', 'filesize' => wp_filesize( dirname( $file ) . '/waffles-10x7.jpg' ), ), + + // #1 array( 'file' => 'waffles-75x50.jpg', 'width' => 75, @@ -251,6 +308,8 @@ public function test_multi_resize() { 'mime-type' => 'image/jpeg', 'filesize' => wp_filesize( dirname( $file ) . '/waffles-75x50.jpg' ), ), + + // #2 array( 'file' => 'waffles-30x20.jpg', 'width' => 30, @@ -258,6 +317,8 @@ public function test_multi_resize() { 'mime-type' => 'image/jpeg', 'filesize' => wp_filesize( dirname( $file ) . '/waffles-30x20.jpg' ), ), + + // #3 array( 'file' => 'waffles-45x400.jpg', 'width' => 45, @@ -265,6 +326,8 @@ public function test_multi_resize() { 'mime-type' => 'image/jpeg', 'filesize' => wp_filesize( dirname( $file ) . '/waffles-45x400.jpg' ), ), + + // #4 array( 'file' => 'waffles-50x33.jpg', 'width' => 50, @@ -272,6 +335,8 @@ public function test_multi_resize() { 'mime-type' => 'image/jpeg', 'filesize' => wp_filesize( dirname( $file ) . '/waffles-50x33.jpg' ), ), + + // #5 array( 'file' => 'waffles-55x37.jpg', 'width' => 55, @@ -279,6 +344,8 @@ public function test_multi_resize() { 'mime-type' => 'image/jpeg', 'filesize' => wp_filesize( dirname( $file ) . '/waffles-55x37.jpg' ), ), + + // #6 array( 'file' => 'waffles-83x55.jpg', 'width' => 83, @@ -286,6 +353,8 @@ public function test_multi_resize() { 'mime-type' => 'image/jpeg', 'filesize' => wp_filesize( dirname( $file ) . '/waffles-83x55.jpg' ), ), + + // #7 array( 'file' => 'waffles-90x60.jpg', 'width' => 90, @@ -293,6 +362,8 @@ public function test_multi_resize() { 'mime-type' => 'image/jpeg', 'filesize' => wp_filesize( dirname( $file ) . '/waffles-90x60.jpg' ), ), + + // #8 array( 'file' => 'waffles-105x70.jpg', 'width' => 105, @@ -300,6 +371,8 @@ public function test_multi_resize() { 'mime-type' => 'image/jpeg', 'filesize' => wp_filesize( dirname( $file ) . '/waffles-105x70.jpg' ), ), + + // #9 array( 'file' => 'waffles-200x133.jpg', 'width' => 200, @@ -315,6 +388,7 @@ public function test_multi_resize() { foreach ( $resized as $key => $image_data ) { $image_path = DIR_TESTDATA . '/images/' . $image_data['file']; + // Now, verify real dimensions are as expected. $this->assertImageDimensions( $image_path, $expected_array[ $key ]['width'], @@ -324,7 +398,7 @@ public function test_multi_resize() { } /** - * Tests resizing with crop enabled. + * Tests resizing an image with cropping. */ public function test_resize_and_crop() { $file = DIR_TESTDATA . '/images/waffles.jpg'; @@ -344,7 +418,7 @@ public function test_resize_and_crop() { } /** - * Tests crop behavior. + * Tests cropping an image. * * @ticket 51937 * @@ -374,27 +448,27 @@ public function test_crop( $src_x, $src_y, $src_w, $src_h, $dst_w = null, $dst_h */ public function data_crop() { return array( - 'src dimensions as ints' => array( + 'src height and width must be greater than 0' => array( 'src_x' => 0, 'src_y' => 0, 'src_w' => 50, 'src_h' => 50, ), - 'src dimensions as numeric strings' => array( + 'src height and width can be string but must be greater than 0' => array( 'src_x' => 10, 'src_y' => '10', 'src_w' => '50', 'src_h' => '50', ), - 'dst dimensions as ints' => array( + 'dst height and width must be greater than 0' => array( 'src_x' => 10, - 'src_y' => 10, + 'src_y' => '10', 'src_w' => 150, 'src_h' => 150, 'dst_w' => 150, 'dst_h' => 150, ), - 'dst dimensions as numeric strings' => array( + 'dst height and width can be string but must be greater than 0' => array( 'src_x' => 10, 'src_y' => '10', 'src_w' => 150, @@ -439,13 +513,13 @@ public function data_crop_invalid_dimensions() { ), 'src width must be greater than 0' => array( 'src_x' => 10, - 'src_y' => 10, + 'src_y' => '10', 'src_w' => 0, 'src_h' => 100, ), 'src height must be numeric and greater than 0' => array( 'src_x' => 10, - 'src_y' => 10, + 'src_y' => '10', 'src_w' => 100, 'src_h' => 'NaN', ), @@ -457,7 +531,7 @@ public function data_crop_invalid_dimensions() { 'dst_w' => '100', 'dst_h' => 'NaN', ), - 'src and dst dimensions must be greater than 0' => array( + 'src and dst height and width must be greater than 0' => array( 'src_x' => 0, 'src_y' => 0, 'src_w' => 0, @@ -465,7 +539,7 @@ public function data_crop_invalid_dimensions() { 'dst_w' => 0, 'dst_h' => 0, ), - 'src and dst dimensions as strings must be greater than 0' => array( + 'src and dst height and width can be string but must be greater than 0' => array( 'src_x' => 0, 'src_y' => 0, 'src_w' => '0', @@ -477,7 +551,7 @@ public function data_crop_invalid_dimensions() { } /** - * Tests rotation behavior. + * Tests rotating an image 180 deg. */ public function test_rotate() { $file = DIR_TESTDATA . '/images/gradient-square.jpg'; @@ -501,36 +575,31 @@ public function test_rotate() { * Tests horizontal flip behavior. */ public function test_flip() { - $file = DIR_TESTDATA . '/images/one-blue-pixel-100x100.png'; + $file = DIR_TESTDATA . '/images/gradient-square.jpg'; $vips_image_editor = new WP_Image_Editor_Vips( $file ); $vips_image_editor->load(); - $save_to_file = tempnam( get_temp_dir(), '' ) . '.png'; - - $result = $vips_image_editor->flip( true, false ); - $vips_image_editor->save( $save_to_file ); - - $this->assertTrue( $result ); - - $verify = new WP_Image_Editor_Vips( $save_to_file ); - $verify->load(); - $property = new ReflectionProperty( $verify, 'image' ); + $property = new ReflectionProperty( $vips_image_editor, 'image' ); if ( PHP_VERSION_ID < 80100 ) { $property->setAccessible( true ); } - $image = $property->getValue( $verify ); + $image = $property->getValue( $vips_image_editor ); if ( ! is_callable( array( $image, 'getpoint' ) ) ) { - unlink( $save_to_file ); $this->markTestSkipped( 'The image editor does not support getpoint().' ); } - $pixel = $image->getpoint( 0, 99 ); - $this->assertSame( 255, (int) $pixel[2] ); + // Get color at top-left before flipping + $color_top_left = $image->getpoint( 0, 0 ); - unlink( $save_to_file ); + $vips_image_editor->flip( true, false ); + + // After vertical flip, top-left should now be at bottom-left (0, 99) + $color_bottom_left = $property->getValue( $vips_image_editor )->getpoint( 0, 99 ); + + $this->assertSame( $color_top_left, $color_bottom_left ); } /** @@ -579,27 +648,68 @@ public function test_streams() { } /** - * @ticket 51665 + * Tests that an image created with WP_Image_Editor_Vips preserves alpha. */ - public function test_directory_creation() { - $file = realpath( DIR_TESTDATA ) . '/images/a2-small.jpg'; - $directory = realpath( DIR_TESTDATA ) . '/images/nonexistent-directory'; + public function test_image_preserves_alpha() { + $file = DIR_TESTDATA . '/images/transparent.png'; $vips_image_editor = new WP_Image_Editor_Vips( $file ); + $vips_image_editor->load(); - $this->assertFileDoesNotExist( $directory ); + $save_to_file = tempnam( get_temp_dir(), '' ) . '.png'; - $loaded = $vips_image_editor->load(); - $this->assertNotWPError( $loaded ); + $vips_image_editor->save( $save_to_file ); - $resized = $vips_image_editor->resize( 100, 100, true ); - $this->assertNotWPError( $resized ); + // Use GD to check the alpha channel since VIPS doesn't have a direct PHP API + $this->assertImageAlphaAtPointGD( $save_to_file, array( 0, 0 ), 127 ); - $saved = $vips_image_editor->save( $directory . '/a2-small-cropped.jpg' ); + unlink( $save_to_file ); + } - unlink( $directory . '/a2-small-cropped.jpg' ); - rmdir( $directory ); + /** + * Tests that an image created with WP_Image_Editor_Vips preserves alpha when resizing. + * + * @ticket 23039 + */ + public function test_image_preserves_alpha_on_resize() { + $file = DIR_TESTDATA . '/images/transparent.png'; - $this->assertNotWPError( $saved ); + $vips_image_editor = new WP_Image_Editor_Vips( $file ); + $vips_image_editor->load(); + + $vips_image_editor->resize( 5, 5 ); + $save_to_file = tempnam( get_temp_dir(), '' ) . '.png'; + + $vips_image_editor->save( $save_to_file ); + + $this->assertImageAlphaAtPointGD( $save_to_file, array( 0, 0 ), 127 ); + + unlink( $save_to_file ); + } + + /** + * Tests that an image created with WP_Image_Editor_Vips preserves alpha when rotating. + * + * @ticket 30596 + */ + public function test_image_preserves_alpha_on_rotate() { + $file = DIR_TESTDATA . '/images/transparent.png'; + + // Get expected alpha from original image + $image = imagecreatefrompng( $file ); + $rgb = imagecolorat( $image, 0, 0 ); + $expected = imagecolorsforindex( $image, $rgb ); + + $vips_image_editor = new WP_Image_Editor_Vips( $file ); + $vips_image_editor->load(); + + $vips_image_editor->rotate( 180 ); + $save_to_file = tempnam( get_temp_dir(), '' ) . '.png'; + + $vips_image_editor->save( $save_to_file ); + + $this->assertImageAlphaAtPointGD( $save_to_file, array( 0, 0 ), $expected['alpha'] ); + + unlink( $save_to_file ); } } From a58b726ed553ce3b9e6143e7b2e3784c12e0143a Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Fri, 25 Sep 2026 11:54:01 -0600 Subject: [PATCH 07/84] PHPCS: Fix coding standard violations in WP_Image_Editor_Vips --- .../class-wp-image-editor-vips.php | 29 +++++++++---------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index 0202f426c8c81..958417e2e4ecc 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -133,14 +133,14 @@ public static function supports_mime_type( $mime_type ) { // Use Image::black() to test write support (encoding) rather than findLoad() which only tests read support (decoding). try { $test_image = Jcupitt\Vips\Image::black( 1, 1 ); - + // Some formats (like GIF) have issues with writeToBuffer in ImageMagick, so test with writeToFile $temp_file = tempnam( sys_get_temp_dir(), 'vips_test_' ) . '.' . $target_extension; - + try { $test_image->writeToFile( $temp_file ); $supported = file_exists( $temp_file ) && filesize( $temp_file ) > 0; - + if ( file_exists( $temp_file ) ) { unlink( $temp_file ); } @@ -315,7 +315,7 @@ public function resize( $max_w, $max_h, $crop = false ) { * @return array An array of resized images metadata by size. */ public function multi_resize( $sizes ) { - $metadata = array(); + $metadata = array(); $orig_size = $this->size; if ( ! $this->original_image ) { @@ -352,7 +352,7 @@ public function multi_resize( $sizes ) { } $resize_result = $this->resize( $size_data['width'], $size_data['height'], $size_data['crop'] ); - $duplicate = ( ( $orig_size['width'] === $size_data['width'] ) && ( $orig_size['height'] === $size_data['height'] ) ); + $duplicate = ( ( $orig_size['width'] === $size_data['width'] ) && ( $orig_size['height'] === $size_data['height'] ) ); if ( ! is_wp_error( $resize_result ) && ! $duplicate ) { $resized = $this->_save( $this->image ); @@ -362,13 +362,12 @@ public function multi_resize( $sizes ) { $metadata[ $size ] = $resized; } } - } // Restore original image and dimensions. try { $this->image = $this->original_image->copy(); - $this->size = $orig_size; + $this->size = $orig_size; } catch ( Exception $e ) { $this->size = $orig_size; } @@ -551,21 +550,21 @@ protected function _save( $image, $filename = null, $mime_type = null ) { switch ( $mime_type ) { case 'image/jpeg': - $save_options['Q'] = $this->get_quality(); + $save_options['Q'] = $this->get_quality(); $save_options['strip'] = true; break; case 'image/png': // PNG quality in VIPS is compression level (0-9). // Convert WP quality (0-100) to VIPS compression (9-0). - $quality = $this->get_quality(); - $compression = 9 - round( ( $quality / 100 ) * 9 ); + $quality = $this->get_quality(); + $compression = 9 - round( ( $quality / 100 ) * 9 ); $save_options['compression'] = max( 0, min( 9, $compression ) ); - $save_options['strip'] = true; + $save_options['strip'] = true; break; case 'image/webp': - $save_options['Q'] = $this->get_quality(); + $save_options['Q'] = $this->get_quality(); $save_options['strip'] = true; break; @@ -574,7 +573,7 @@ protected function _save( $image, $filename = null, $mime_type = null ) { break; case 'image/avif': - $save_options['Q'] = $this->get_quality(); + $save_options['Q'] = $this->get_quality(); $save_options['strip'] = true; break; } @@ -643,8 +642,8 @@ public function stream( $mime_type = null ) { switch ( $mime_type ) { case 'image/png': - $quality = $this->get_quality(); - $compression = 9 - round( ( $quality / 100 ) * 9 ); + $quality = $this->get_quality(); + $compression = 9 - round( ( $quality / 100 ) * 9 ); $save_options['compression'] = max( 0, min( 9, $compression ) ); break; From d33a372b0d2070d2e7d9f55d53f353bf17339759 Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Fri, 25 Sep 2026 11:59:12 -0600 Subject: [PATCH 08/84] PHPStan: Fix static analysis errors in WP_Image_Editor_Vips --- .../class-wp-image-editor-vips.php | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index 958417e2e4ecc..54025be9fdfd4 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -17,7 +17,7 @@ class WP_Image_Editor_Vips extends WP_Image_Editor { /** * VIPS Image object. * - * @var Jcupitt\Vips\Image + * @var Jcupitt\Vips\Image|null */ protected $image; @@ -192,10 +192,6 @@ public function load() { $this->image = Jcupitt\Vips\Image::newFromFile( $this->file ); } - if ( ! $this->image ) { - return new WP_Error( 'invalid_image', __( 'File is not an image.' ), $this->file ); - } - // Get image size. $width = $this->image->width; $height = $this->image->height; @@ -230,11 +226,11 @@ public function load() { * * @since 6.8.0 * - * @param int $width - * @param int $height + * @param int|null $width Image width. + * @param int|null $height Image height. * @return true */ - protected function update_size( $width = false, $height = false ) { + protected function update_size( $width = null, $height = null ) { if ( ! $width ) { $width = $this->image->width; } @@ -615,6 +611,13 @@ protected function _save( $image, $filename = null, $mime_type = null ) { return array( 'path' => $filename, + /** + * Filters the name of the saved image file. + * + * @since 2.6.0 + * + * @param string $filename Name of the file. + */ 'file' => wp_basename( apply_filters( 'image_make_intermediate_size', $filename ) ), 'width' => $this->size['width'], 'height' => $this->size['height'], From 168976102808394d112daf7cffc383c4e8dc29eb Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Fri, 25 Sep 2026 12:00:49 -0600 Subject: [PATCH 09/84] Composer: Move jcupitt/vips out of runtime requirements --- composer.json | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/composer.json b/composer.json index a95aeaa6f0927..40a72ca0a8d29 100644 --- a/composer.json +++ b/composer.json @@ -13,8 +13,7 @@ "require": { "ext-hash": "*", "ext-json": "*", - "php": ">=7.4", - "jcupitt/vips": "*" + "php": ">=7.4" }, "suggest": { "ext-apcu": "*", From b9132fc4edcf4b66a2095ca18545fb9002dae133 Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Fri, 25 Sep 2026 12:01:46 -0600 Subject: [PATCH 10/84] Media: Register VIPS image editor last instead of first --- src/wp-includes/media.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/wp-includes/media.php b/src/wp-includes/media.php index 1fa29f79a2503..5d0d9d3ed94ae 100644 --- a/src/wp-includes/media.php +++ b/src/wp-includes/media.php @@ -4430,9 +4430,9 @@ function _wp_image_editor_choose( $args = array() ) { * @since 3.5.0 * * @param string[] $image_editors Array of available image editor class names. Defaults are - * 'WP_Image_Editor_Vips', 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD'. + * 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD', 'WP_Image_Editor_Vips'. */ - $implementations = apply_filters( 'wp_image_editors', array( 'WP_Image_Editor_Vips', 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD' ) ); + $implementations = apply_filters( 'wp_image_editors', array( 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD', 'WP_Image_Editor_Vips' ) ); $editors = wp_cache_get( 'wp_image_editor_choose', 'image_editor' ); From 2e9fdbcb80c3b8807bc8aecba7773cd83fe31879 Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Fri, 25 Sep 2026 12:02:36 -0600 Subject: [PATCH 11/84] VIPS: Fix temp file leak in encoder support probe --- .../class-wp-image-editor-vips.php | 27 +++++++++++++------ 1 file changed, 19 insertions(+), 8 deletions(-) diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index 54025be9fdfd4..acbffed7afd07 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -134,21 +134,32 @@ public static function supports_mime_type( $mime_type ) { try { $test_image = Jcupitt\Vips\Image::black( 1, 1 ); - // Some formats (like GIF) have issues with writeToBuffer in ImageMagick, so test with writeToFile - $temp_file = tempnam( sys_get_temp_dir(), 'vips_test_' ) . '.' . $target_extension; + // libvips selects the encoder from the file suffix, so the probe is written + // to a suffixed file. tempnam() creates the unsuffixed file itself, and both + // are removed once the probe has run. + $temp_file = tempnam( sys_get_temp_dir(), 'vips_test_' ); - try { - $test_image->writeToFile( $temp_file ); - $supported = file_exists( $temp_file ) && filesize( $temp_file ) > 0; + if ( false === $temp_file ) { + self::$mime_support_cache[ $mime_type ] = false; - if ( file_exists( $temp_file ) ) { - unlink( $temp_file ); - } + return false; + } + + $probe_file = $temp_file . '.' . $target_extension; + + try { + $test_image->writeToFile( $probe_file ); + $supported = file_exists( $probe_file ) && filesize( $probe_file ) > 0; } catch ( Exception $write_error ) { $supported = false; + } finally { if ( file_exists( $temp_file ) ) { unlink( $temp_file ); } + + if ( file_exists( $probe_file ) ) { + unlink( $probe_file ); + } } self::$mime_support_cache[ $mime_type ] = $supported; From 652f32049ede5209e052fa6ab54a8b462b9e0af1 Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Fri, 25 Sep 2026 12:03:40 -0600 Subject: [PATCH 12/84] Update API: Report VIPS JPEG XL support instead of hardcoding false --- src/wp-includes/update.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/wp-includes/update.php b/src/wp-includes/update.php index 0543db369eac9..64576288364ee 100644 --- a/src/wp-includes/update.php +++ b/src/wp-includes/update.php @@ -190,7 +190,7 @@ function ( $carry, $prefixed_myisam_table ) use ( $all_unprefixed_tables ) { 'webp' => WP_Image_Editor_Vips::supports_mime_type( 'image/webp' ), 'avif' => WP_Image_Editor_Vips::supports_mime_type( 'image/avif' ), 'heic' => WP_Image_Editor_Vips::supports_mime_type( 'image/heic' ), - 'jxl' => false, + 'jxl' => WP_Image_Editor_Vips::supports_mime_type( 'image/jxl' ), ) ) ); From 2d6d53f254c66cd9f52043493647c641294fdece Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Fri, 25 Sep 2026 12:06:19 -0600 Subject: [PATCH 13/84] Update API: Load VIPS editor safely and gate reporting on a working backend --- src/wp-includes/update.php | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/src/wp-includes/update.php b/src/wp-includes/update.php index 64576288364ee..1b502385e8378 100644 --- a/src/wp-includes/update.php +++ b/src/wp-includes/update.php @@ -180,20 +180,23 @@ function ( $carry, $prefixed_myisam_table ) use ( $all_unprefixed_tables ) { ); } - if ( extension_loaded( 'ffi' ) && class_exists( 'Jcupitt\\Vips\\Config' ) && class_exists( 'Jcupitt\\Vips\\Image' ) ) { + if ( extension_loaded( 'ffi' ) ) { + require_once ABSPATH . WPINC . '/class-wp-image-editor.php'; require_once ABSPATH . WPINC . '/class-wp-image-editor-vips.php'; - // Add data for libvips WebP, AVIF, HEIC and JPEG XL support. - $query['image_support']['vips'] = array_keys( - array_filter( - array( - 'webp' => WP_Image_Editor_Vips::supports_mime_type( 'image/webp' ), - 'avif' => WP_Image_Editor_Vips::supports_mime_type( 'image/avif' ), - 'heic' => WP_Image_Editor_Vips::supports_mime_type( 'image/heic' ), - 'jxl' => WP_Image_Editor_Vips::supports_mime_type( 'image/jxl' ), + if ( WP_Image_Editor_Vips::test() ) { + // Add data for libvips WebP, AVIF, HEIC and JPEG XL support. + $query['image_support']['vips'] = array_keys( + array_filter( + array( + 'webp' => WP_Image_Editor_Vips::supports_mime_type( 'image/webp' ), + 'avif' => WP_Image_Editor_Vips::supports_mime_type( 'image/avif' ), + 'heic' => WP_Image_Editor_Vips::supports_mime_type( 'image/heic' ), + 'jxl' => WP_Image_Editor_Vips::supports_mime_type( 'image/jxl' ), + ) ) - ) - ); + ); + } } /** From 31c57050eaca4a9269e28b776b290fbb18d17987 Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Fri, 25 Sep 2026 12:07:04 -0600 Subject: [PATCH 14/84] Admin: Fix VIPS capability detection in debug data and site health --- src/wp-admin/includes/class-wp-debug-data.php | 7 ++++++- src/wp-admin/includes/class-wp-site-health.php | 12 +++++------- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/src/wp-admin/includes/class-wp-debug-data.php b/src/wp-admin/includes/class-wp-debug-data.php index 2339b7bbd0e07..9dcc13414e9f4 100644 --- a/src/wp-admin/includes/class-wp-debug-data.php +++ b/src/wp-admin/includes/class-wp-debug-data.php @@ -824,7 +824,12 @@ private static function get_wp_media(): array { ); } - if ( class_exists( 'WP_Image_Editor_Vips' ) ) { + if ( extension_loaded( 'ffi' ) && ! class_exists( 'WP_Image_Editor_Vips' ) ) { + require_once ABSPATH . WPINC . '/class-wp-image-editor.php'; + require_once ABSPATH . WPINC . '/class-wp-image-editor-vips.php'; + } + + if ( class_exists( 'WP_Image_Editor_Vips' ) && WP_Image_Editor_Vips::test() ) { $vips_image_formats = array(); $vips_formats = array( 'JPEG' => 'image/jpeg', diff --git a/src/wp-admin/includes/class-wp-site-health.php b/src/wp-admin/includes/class-wp-site-health.php index 2056afaa23670..b9e95387f65e2 100644 --- a/src/wp-admin/includes/class-wp-site-health.php +++ b/src/wp-admin/includes/class-wp-site-health.php @@ -1032,15 +1032,13 @@ public function get_test_php_extensions() { 'required' => false, 'fallback_for' => 'zip', ), + 'vips' => array( + 'extension' => 'ffi', + 'required' => false, + 'fallback_for' => 'imagick', + ), ); - if ( class_exists( 'Jcupitt\\Vips\\Image' ) ) { - $modules['vips'] = array( - 'class' => 'Jcupitt\\Vips\\Image', - 'required' => false, - ); - } - /** * Filters the array representing all the modules we wish to test for. * From 9dedb56de8b23ab3dcd2ca029b13e19a61303d28 Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Fri, 25 Sep 2026 12:08:33 -0600 Subject: [PATCH 15/84] VIPS: Remove redundant destructor nulling --- src/wp-includes/class-wp-image-editor-vips.php | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index acbffed7afd07..dfe9c6237a6da 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -38,17 +38,6 @@ class WP_Image_Editor_Vips extends WP_Image_Editor { */ protected static $mime_support_cache = array(); - public function __destruct() { - if ( $this->image ) { - // VIPS uses reference counting and automatic memory management. - $this->image = null; - } - - if ( $this->original_image ) { - $this->original_image = null; - } - } - /** * Checks to see if current environment supports VIPS. * From f14855a41d59ddd19d286f24ca4d420322567bad Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Fri, 25 Sep 2026 12:09:16 -0600 Subject: [PATCH 16/84] Docs: Update @since tags for the VIPS image editor --- .../class-wp-image-editor-vips.php | 26 +++++++++---------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index dfe9c6237a6da..43cdeb9c48278 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -9,7 +9,7 @@ /** * WordPress Image Editor Class for Image Manipulation through VIPS * - * @since 6.8.0 + * @since 7.2.0 * * @see WP_Image_Editor */ @@ -41,7 +41,7 @@ class WP_Image_Editor_Vips extends WP_Image_Editor { /** * Checks to see if current environment supports VIPS. * - * @since 6.8.0 + * @since 7.2.0 * * @param array $args * @return bool @@ -78,7 +78,7 @@ public static function test( $args = array() ) { /** * Checks to see if editor supports the mime-type specified. * - * @since 6.8.0 + * @since 7.2.0 * * @param string $mime_type * @return bool @@ -164,7 +164,7 @@ public static function supports_mime_type( $mime_type ) { /** * Loads image from $this->file into new VIPS Image object. * - * @since 6.8.0 + * @since 7.2.0 * * @return true|WP_Error True if loaded successfully; WP_Error on failure. */ @@ -224,7 +224,7 @@ public function load() { /** * Sets or updates current image size. * - * @since 6.8.0 + * @since 7.2.0 * * @param int|null $width Image width. * @param int|null $height Image height. @@ -248,7 +248,7 @@ protected function update_size( $width = null, $height = null ) { * At minimum, either a height or width must be provided. If one of the two is set * to null, the resize will maintain aspect ratio according to the provided dimension. * - * @since 6.8.0 + * @since 7.2.0 * * @param int|null $max_w Image width. * @param int|null $max_h Image height. @@ -297,7 +297,7 @@ public function resize( $max_w, $max_h, $crop = false ) { /** * Resize multiple images from a single source. * - * @since 6.8.0 + * @since 7.2.0 * * @param array $sizes { * An array of image size arrays. Default sizes are 'small', 'medium', 'large'. @@ -374,7 +374,7 @@ public function multi_resize( $sizes ) { /** * Crops Image. * - * @since 6.8.0 + * @since 7.2.0 * * @param int $src_x The start x position to crop from. * @param int $src_y The start y position to crop from. @@ -434,7 +434,7 @@ public function crop( $src_x, $src_y, $src_w, $src_h, $dst_w = null, $dst_h = nu /** * Rotates current image counter-clockwise by $angle. * - * @since 6.8.0 + * @since 7.2.0 * * @param float $angle * @return true|WP_Error @@ -470,7 +470,7 @@ public function rotate( $angle ) { /** * Flips current image. * - * @since 6.8.0 + * @since 7.2.0 * * @param bool $horz Flip along Horizontal Axis * @param bool $vert Flip along Vertical Axis @@ -497,7 +497,7 @@ public function flip( $horz, $vert ) { /** * Saves current image to file. * - * @since 6.8.0 + * @since 7.2.0 * * @param string $destfilename Optional. Destination filename. Default null. * @param string $mime_type Optional. The mime-type. Default null. @@ -526,7 +526,7 @@ public function save( $destfilename = null, $mime_type = null ) { /** * Internal save method. * - * @since 6.8.0 + * @since 7.2.0 * * @param Jcupitt\Vips\Image $image * @param string $filename @@ -632,7 +632,7 @@ protected function _save( $image, $filename = null, $mime_type = null ) { /** * Streams current image to browser. * - * @since 6.8.0 + * @since 7.2.0 * * @param string $mime_type Optional. The mime type of the image. Default is the original mime type. * @return true|WP_Error True on success, WP_Error object on failure. From 7c77bd80b0a7a981456add1c3b3c367f8a2aed69 Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Fri, 25 Sep 2026 12:10:26 -0600 Subject: [PATCH 17/84] Local env: Document VIPS container dependencies --- tools/local-env/php-vips/Dockerfile | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/tools/local-env/php-vips/Dockerfile b/tools/local-env/php-vips/Dockerfile index 488c8087f4a19..6c6373a8fec72 100644 --- a/tools/local-env/php-vips/Dockerfile +++ b/tools/local-env/php-vips/Dockerfile @@ -1,17 +1,20 @@ ARG LOCAL_PHP=latest FROM wordpressdevelop/php:${LOCAL_PHP} +# libvips42 is the library the binding loads. libffi-dev is required to compile the FFI +# extension that performs the loading, and is otherwise only pulled in transitively by +# the libvips development packages. RUN set -eux; \ apt-get update; \ - apt-get install -y --no-install-recommends libvips42 libvips-dev; \ + apt-get install -y --no-install-recommends libvips42 libffi-dev; \ rm -rf /var/lib/apt/lists/* -# Install and enable FFI PHP extension +# Install and enable the FFI extension. RUN set -eux; \ docker-php-ext-install ffi; \ docker-php-ext-enable ffi -# Configure FFI and stack size for VIPS +# Enable FFI, and disable the stack size check that libvips' native call depth can trip. RUN set -eux; \ { \ echo 'ffi.enable=1'; \ From e73b76396240f28f9ba36b34aa4fbf22ee78ef0b Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Fri, 25 Sep 2026 12:11:28 -0600 Subject: [PATCH 18/84] Local env: Resolve the VIPS compose file from the repo root --- tools/local-env/scripts/utils.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/local-env/scripts/utils.js b/tools/local-env/scripts/utils.js index f2b607efe2d2f..8782202198039 100644 --- a/tools/local-env/scripts/utils.js +++ b/tools/local-env/scripts/utils.js @@ -92,7 +92,7 @@ const local_env_utils = { const composeFiles = [ 'docker-compose.yml' ]; const shouldUseVips = process.env.LOCAL_PHP_VIPS === 'true'; - if ( shouldUseVips && existsSync( 'docker-compose.vips.yml' ) ) { + if ( shouldUseVips && existsSync( join( repo_root, 'docker-compose.vips.yml' ) ) ) { composeFiles.push( 'docker-compose.vips.yml' ); } From da3867ab3ab0aacccb4e489683f3036ed0b262a2 Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Fri, 25 Sep 2026 12:12:10 -0600 Subject: [PATCH 19/84] Tests: Assert VIPS flip behaviour instead of internals --- tests/phpunit/tests/image/editorVips.php | 44 ++++++++++++++++-------- 1 file changed, 29 insertions(+), 15 deletions(-) diff --git a/tests/phpunit/tests/image/editorVips.php b/tests/phpunit/tests/image/editorVips.php index a64efe94f42ad..05897f127d78c 100644 --- a/tests/phpunit/tests/image/editorVips.php +++ b/tests/phpunit/tests/image/editorVips.php @@ -572,34 +572,48 @@ public function test_rotate() { } /** - * Tests horizontal flip behavior. + * Tests that flipping along the horizontal axis mirrors the image vertically. */ public function test_flip() { $file = DIR_TESTDATA . '/images/gradient-square.jpg'; + // Save a lossless copy of the unmodified image to sample the source pixels from. + $original_editor = new WP_Image_Editor_Vips( $file ); + $original_editor->load(); + + $size = $original_editor->get_size(); + $original_tmp = tempnam( get_temp_dir(), 'vips_flip_' ); + $original_file = $original_tmp . '.png'; + $original_editor->save( $original_file ); + $vips_image_editor = new WP_Image_Editor_Vips( $file ); $vips_image_editor->load(); - $property = new ReflectionProperty( $vips_image_editor, 'image' ); + $flipped = $vips_image_editor->flip( true, false ); + $this->assertTrue( $flipped ); - if ( PHP_VERSION_ID < 80100 ) { - $property->setAccessible( true ); - } + $flipped_tmp = tempnam( get_temp_dir(), 'vips_flip_' ); + $flipped_file = $flipped_tmp . '.png'; + $vips_image_editor->save( $flipped_file ); - $image = $property->getValue( $vips_image_editor ); - if ( ! is_callable( array( $image, 'getpoint' ) ) ) { - $this->markTestSkipped( 'The image editor does not support getpoint().' ); - } + $original_image = imagecreatefrompng( $original_file ); + $flipped_image = imagecreatefrompng( $flipped_file ); - // Get color at top-left before flipping - $color_top_left = $image->getpoint( 0, 0 ); + // Flipping along the horizontal axis moves the bottom-left pixel to the top-left. + $expected = imagecolorsforindex( $original_image, imagecolorat( $original_image, 0, $size['height'] - 1 ) ); + $actual = imagecolorsforindex( $flipped_image, imagecolorat( $flipped_image, 0, 0 ) ); - $vips_image_editor->flip( true, false ); + imagedestroy( $original_image ); + imagedestroy( $flipped_image ); - // After vertical flip, top-left should now be at bottom-left (0, 99) - $color_bottom_left = $property->getValue( $vips_image_editor )->getpoint( 0, 99 ); + unlink( $original_tmp ); + unlink( $original_file ); + unlink( $flipped_tmp ); + unlink( $flipped_file ); - $this->assertSame( $color_top_left, $color_bottom_left ); + $this->assertSame( $expected['red'], $actual['red'] ); + $this->assertSame( $expected['green'], $actual['green'] ); + $this->assertSame( $expected['blue'], $actual['blue'] ); } /** From 40c1b49018ffe479932bd5261d463d675fd2c952 Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Fri, 25 Sep 2026 13:25:34 -0600 Subject: [PATCH 20/84] Local env: Build the VIPS image on env:start --- docker-compose.vips.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docker-compose.vips.yml b/docker-compose.vips.yml index 26b6b98860125..bc38d9981116c 100644 --- a/docker-compose.vips.yml +++ b/docker-compose.vips.yml @@ -5,3 +5,7 @@ services: dockerfile: tools/local-env/php-vips/Dockerfile args: LOCAL_PHP: ${LOCAL_PHP-latest} + + # `up` only builds when the image is missing, and the base image is always present, + # so without this the VIPS image would never be built and the VIPS tests would skip. + pull_policy: build From 7c2c35ba4fe083ad0bcbb69caed2c9d47a4315df Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Fri, 25 Sep 2026 13:26:33 -0600 Subject: [PATCH 21/84] Media: Prefer the VIPS editor when available --- src/wp-includes/media.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/wp-includes/media.php b/src/wp-includes/media.php index 5d0d9d3ed94ae..1fa29f79a2503 100644 --- a/src/wp-includes/media.php +++ b/src/wp-includes/media.php @@ -4430,9 +4430,9 @@ function _wp_image_editor_choose( $args = array() ) { * @since 3.5.0 * * @param string[] $image_editors Array of available image editor class names. Defaults are - * 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD', 'WP_Image_Editor_Vips'. + * 'WP_Image_Editor_Vips', 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD'. */ - $implementations = apply_filters( 'wp_image_editors', array( 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD', 'WP_Image_Editor_Vips' ) ); + $implementations = apply_filters( 'wp_image_editors', array( 'WP_Image_Editor_Vips', 'WP_Image_Editor_Imagick', 'WP_Image_Editor_GD' ) ); $editors = wp_cache_get( 'wp_image_editor_choose', 'image_editor' ); From b86cabf26587ce82f458b7640141f7df5546ca6b Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Fri, 25 Sep 2026 13:27:23 -0600 Subject: [PATCH 22/84] VIPS: Honour the image_strip_meta filter --- .../class-wp-image-editor-imagick.php | 4 +- .../class-wp-image-editor-vips.php | 13 +++--- tests/phpunit/tests/image/editorVips.php | 41 +++++++++++++++++++ 3 files changed, 51 insertions(+), 7 deletions(-) diff --git a/src/wp-includes/class-wp-image-editor-imagick.php b/src/wp-includes/class-wp-image-editor-imagick.php index 0be31905eae81..f3dd8e9fff06c 100644 --- a/src/wp-includes/class-wp-image-editor-imagick.php +++ b/src/wp-includes/class-wp-image-editor-imagick.php @@ -635,8 +635,8 @@ protected function thumbnail_image( $dst_w, $dst_h, $filter_name = 'FILTER_TRIAN /** * Filters whether to strip metadata from images when they're resized. * - * This filter only applies when resizing using the Imagick editor since GD - * always strips profiles by default. + * This filter only applies when resizing using the Imagick or VIPS editors, + * since GD always strips profiles by default. * * @since 4.5.0 * diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index 43cdeb9c48278..2425cdb37a1c3 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -544,10 +544,13 @@ protected function _save( $image, $filename = null, $mime_type = null ) { // Prepare save options based on mime type. $save_options = array(); + /** This filter is documented in wp-includes/class-wp-image-editor-imagick.php */ + $strip_meta = apply_filters( 'image_strip_meta', true ); + switch ( $mime_type ) { case 'image/jpeg': $save_options['Q'] = $this->get_quality(); - $save_options['strip'] = true; + $save_options['strip'] = $strip_meta; break; case 'image/png': @@ -556,21 +559,21 @@ protected function _save( $image, $filename = null, $mime_type = null ) { $quality = $this->get_quality(); $compression = 9 - round( ( $quality / 100 ) * 9 ); $save_options['compression'] = max( 0, min( 9, $compression ) ); - $save_options['strip'] = true; + $save_options['strip'] = $strip_meta; break; case 'image/webp': $save_options['Q'] = $this->get_quality(); - $save_options['strip'] = true; + $save_options['strip'] = $strip_meta; break; case 'image/gif': - $save_options['strip'] = true; + $save_options['strip'] = $strip_meta; break; case 'image/avif': $save_options['Q'] = $this->get_quality(); - $save_options['strip'] = true; + $save_options['strip'] = $strip_meta; break; } diff --git a/tests/phpunit/tests/image/editorVips.php b/tests/phpunit/tests/image/editorVips.php index 05897f127d78c..16ae84aabdb32 100644 --- a/tests/phpunit/tests/image/editorVips.php +++ b/tests/phpunit/tests/image/editorVips.php @@ -726,4 +726,45 @@ public function test_image_preserves_alpha_on_rotate() { unlink( $save_to_file ); } + + /** + * Tests that the image_strip_meta filter controls whether metadata is stripped. + * + * @requires extension exif + */ + public function test_image_strip_meta_filter() { + $file = DIR_TESTDATA . '/images/test-image-iptc.jpg'; + + $strip_meta = static function () { + return false; + }; + + // Metadata is stripped by default. + $vips_image_editor = new WP_Image_Editor_Vips( $file ); + $vips_image_editor->load(); + + $stripped_file = tempnam( get_temp_dir(), 'vips_meta_' ) . '.jpg'; + $vips_image_editor->save( $stripped_file ); + + $stripped = wp_read_image_metadata( $stripped_file ); + unlink( $stripped_file ); + + $this->assertEmpty( $stripped['caption'], 'Metadata should be stripped by default.' ); + + // The filter can prevent stripping. + add_filter( 'image_strip_meta', $strip_meta ); + + $vips_image_editor = new WP_Image_Editor_Vips( $file ); + $vips_image_editor->load(); + + $preserved_file = tempnam( get_temp_dir(), 'vips_meta_' ) . '.jpg'; + $vips_image_editor->save( $preserved_file ); + + remove_filter( 'image_strip_meta', $strip_meta ); + + $preserved = wp_read_image_metadata( $preserved_file ); + unlink( $preserved_file ); + + $this->assertNotEmpty( $preserved['caption'], 'Metadata should be preserved when the filter returns false.' ); + } } From b54aef65d31d02cc70bc3ec4b09ceef7926b861f Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Fri, 25 Sep 2026 13:32:34 -0600 Subject: [PATCH 23/84] Tests: Cover repeated reads from a single VIPS editor instance --- tests/phpunit/tests/image/editorVips.php | 30 ++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/tests/phpunit/tests/image/editorVips.php b/tests/phpunit/tests/image/editorVips.php index 16ae84aabdb32..a27ad1dfaaadc 100644 --- a/tests/phpunit/tests/image/editorVips.php +++ b/tests/phpunit/tests/image/editorVips.php @@ -767,4 +767,34 @@ public function test_image_strip_meta_filter() { $this->assertNotEmpty( $preserved['caption'], 'Metadata should be preserved when the filter returns false.' ); } + + /** + * Tests that a single loaded image can be read more than once. + * + * The source must not be opened with sequential access, which permits only one pass + * and fails the second read with a "VipsJpeg: out of order read" error. + */ + public function test_repeated_reads_from_one_instance() { + $file = DIR_TESTDATA . '/images/waffles.jpg'; + + $vips_image_editor = new WP_Image_Editor_Vips( $file ); + $vips_image_editor->load(); + + $size = $vips_image_editor->get_size(); + + $first_file = tempnam( get_temp_dir(), 'vips_reads_' ) . '.jpg'; + $second_file = tempnam( get_temp_dir(), 'vips_reads_' ) . '.jpg'; + + $first = $vips_image_editor->save( $first_file ); + $second = $vips_image_editor->save( $second_file ); + + $this->assertNotWPError( $first ); + $this->assertNotWPError( $second ); + + $this->assertImageDimensions( $first_file, $size['width'], $size['height'] ); + $this->assertImageDimensions( $second_file, $size['width'], $size['height'] ); + + unlink( $first_file ); + unlink( $second_file ); + } } From 6f9c2b0cc3bce0218171b4154d208566a393a35b Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Fri, 25 Sep 2026 13:35:02 -0600 Subject: [PATCH 24/84] Local env: Give the VIPS image its own tag and build it in one layer --- docker-compose.vips.yml | 6 ++++++ tools/local-env/php-vips/Dockerfile | 17 +++++++++-------- 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/docker-compose.vips.yml b/docker-compose.vips.yml index bc38d9981116c..5fa1628e64690 100644 --- a/docker-compose.vips.yml +++ b/docker-compose.vips.yml @@ -1,5 +1,11 @@ services: php: + # The VIPS image gets its own tag. Building it over the base image's tag would + # overwrite the base, so each rebuild would stack another layer on the previous + # build's output instead of on the base. The overlayfs layer limit is low enough + # that a couple of rebuilds would then break both the build and container creation. + image: wordpressdevelop/php-vips:${LOCAL_PHP-latest} + build: context: . dockerfile: tools/local-env/php-vips/Dockerfile diff --git a/tools/local-env/php-vips/Dockerfile b/tools/local-env/php-vips/Dockerfile index 6c6373a8fec72..445a9cea3c7db 100644 --- a/tools/local-env/php-vips/Dockerfile +++ b/tools/local-env/php-vips/Dockerfile @@ -1,21 +1,22 @@ ARG LOCAL_PHP=latest FROM wordpressdevelop/php:${LOCAL_PHP} +# Everything is installed in a single layer on purpose. The published base image sits +# at the overlayfs layering limit, so a second layer of our own is enough to make the +# build fail with "max depth exceeded". +# # libvips42 is the library the binding loads. libffi-dev is required to compile the FFI # extension that performs the loading, and is otherwise only pulled in transitively by # the libvips development packages. +# +# FFI is enabled, and the stack size check is disabled because libvips' native call +# depth can trip it. RUN set -eux; \ apt-get update; \ apt-get install -y --no-install-recommends libvips42 libffi-dev; \ - rm -rf /var/lib/apt/lists/* - -# Install and enable the FFI extension. -RUN set -eux; \ + rm -rf /var/lib/apt/lists/*; \ docker-php-ext-install ffi; \ - docker-php-ext-enable ffi - -# Enable FFI, and disable the stack size check that libvips' native call depth can trip. -RUN set -eux; \ + docker-php-ext-enable ffi; \ { \ echo 'ffi.enable=1'; \ echo 'zend.max_allowed_stack_size=-1'; \ From aee40ce806ca00c202eb21687f38a933220d067c Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Fri, 25 Sep 2026 13:35:02 -0600 Subject: [PATCH 25/84] Vendor jcupitt/vips and psr/log into src/wp-includes --- composer.json | 3 +- phpcs.xml.dist | 1 + .../class-wp-image-editor-vips.php | 5 + src/wp-includes/php-vips/LICENSE.txt | 20 + src/wp-includes/php-vips/autoload.php | 45 + src/wp-includes/php-vips/src/Access.php | 54 + src/wp-includes/php-vips/src/Align.php | 54 + src/wp-includes/php-vips/src/Angle.php | 55 + src/wp-includes/php-vips/src/Angle45.php | 59 + .../php-vips/src/ArgumentFlags.php | 58 + src/wp-includes/php-vips/src/BandFormat.php | 62 + src/wp-includes/php-vips/src/BlendMode.php | 76 + src/wp-includes/php-vips/src/Coding.php | 55 + src/wp-includes/php-vips/src/Combine.php | 54 + src/wp-includes/php-vips/src/CombineMode.php | 53 + .../php-vips/src/CompassDirection.php | 60 + src/wp-includes/php-vips/src/Config.php | 160 ++ src/wp-includes/php-vips/src/Connection.php | 33 + src/wp-includes/php-vips/src/DebugLogger.php | 87 + src/wp-includes/php-vips/src/Direction.php | 53 + src/wp-includes/php-vips/src/Exception.php | 70 + src/wp-includes/php-vips/src/Extend.php | 57 + src/wp-includes/php-vips/src/FFI.php | 766 ++++++ src/wp-includes/php-vips/src/FailOn.php | 55 + .../php-vips/src/ForeignDzContainer.php | 54 + .../php-vips/src/ForeignDzDepth.php | 54 + .../php-vips/src/ForeignDzLayout.php | 56 + .../php-vips/src/ForeignHeifCompression.php | 55 + .../php-vips/src/ForeignHeifEncoder.php | 56 + src/wp-includes/php-vips/src/ForeignKeep.php | 59 + .../php-vips/src/ForeignPdfPageBox.php | 56 + .../php-vips/src/ForeignPngFilter.php | 57 + .../php-vips/src/ForeignPpmFormat.php | 56 + .../php-vips/src/ForeignSubsample.php | 54 + .../php-vips/src/ForeignTiffCompression.php | 60 + .../php-vips/src/ForeignTiffPredictor.php | 54 + .../php-vips/src/ForeignTiffResunit.php | 53 + .../php-vips/src/ForeignWebpPreset.php | 57 + src/wp-includes/php-vips/src/GObject.php | 219 ++ src/wp-includes/php-vips/src/GValue.php | 287 +++ src/wp-includes/php-vips/src/Image.php | 2224 +++++++++++++++++ src/wp-includes/php-vips/src/ImageAutodoc.php | 758 ++++++ src/wp-includes/php-vips/src/Intent.php | 56 + src/wp-includes/php-vips/src/Interesting.php | 58 + src/wp-includes/php-vips/src/Interpolate.php | 98 + .../php-vips/src/Interpretation.php | 73 + src/wp-includes/php-vips/src/Introspect.php | 202 ++ src/wp-includes/php-vips/src/Kernel.php | 59 + .../php-vips/src/OperationBoolean.php | 56 + .../php-vips/src/OperationComplex.php | 54 + .../php-vips/src/OperationComplex2.php | 52 + .../php-vips/src/OperationComplexget.php | 53 + .../php-vips/src/OperationMath.php | 67 + .../php-vips/src/OperationMath2.php | 54 + .../php-vips/src/OperationMorphology.php | 53 + .../php-vips/src/OperationRelational.php | 57 + .../php-vips/src/OperationRound.php | 54 + src/wp-includes/php-vips/src/PCS.php | 53 + src/wp-includes/php-vips/src/Precision.php | 54 + src/wp-includes/php-vips/src/RegionShrink.php | 57 + src/wp-includes/php-vips/src/SdfShape.php | 55 + src/wp-includes/php-vips/src/Size.php | 55 + src/wp-includes/php-vips/src/Source.php | 81 + src/wp-includes/php-vips/src/SourceCustom.php | 50 + .../php-vips/src/SourceResource.php | 36 + src/wp-includes/php-vips/src/Target.php | 74 + src/wp-includes/php-vips/src/TargetCustom.php | 105 + .../php-vips/src/TargetResource.php | 48 + src/wp-includes/php-vips/src/TextWrap.php | 55 + src/wp-includes/php-vips/src/Utils.php | 116 + src/wp-includes/php-vips/src/VipsObject.php | 175 ++ .../php-vips/src/VipsOperation.php | 319 +++ .../third-party/Psr/Log/AbstractLogger.php | 15 + .../Psr/Log/InvalidArgumentException.php | 7 + .../php-vips/third-party/Psr/Log/LICENSE | 19 + .../php-vips/third-party/Psr/Log/LogLevel.php | 18 + .../Psr/Log/LoggerAwareInterface.php | 14 + .../third-party/Psr/Log/LoggerAwareTrait.php | 21 + .../third-party/Psr/Log/LoggerInterface.php | 90 + .../third-party/Psr/Log/LoggerTrait.php | 90 + .../third-party/Psr/Log/NullLogger.php | 26 + tests/phpstan/base.neon | 1 + tools/php-vips/README.md | 58 + tools/php-vips/installer.sh | 331 +++ tools/php-vips/scoper.inc.php | 53 + 85 files changed, 9384 insertions(+), 2 deletions(-) create mode 100644 src/wp-includes/php-vips/LICENSE.txt create mode 100644 src/wp-includes/php-vips/autoload.php create mode 100644 src/wp-includes/php-vips/src/Access.php create mode 100644 src/wp-includes/php-vips/src/Align.php create mode 100644 src/wp-includes/php-vips/src/Angle.php create mode 100644 src/wp-includes/php-vips/src/Angle45.php create mode 100644 src/wp-includes/php-vips/src/ArgumentFlags.php create mode 100644 src/wp-includes/php-vips/src/BandFormat.php create mode 100644 src/wp-includes/php-vips/src/BlendMode.php create mode 100644 src/wp-includes/php-vips/src/Coding.php create mode 100644 src/wp-includes/php-vips/src/Combine.php create mode 100644 src/wp-includes/php-vips/src/CombineMode.php create mode 100644 src/wp-includes/php-vips/src/CompassDirection.php create mode 100644 src/wp-includes/php-vips/src/Config.php create mode 100644 src/wp-includes/php-vips/src/Connection.php create mode 100644 src/wp-includes/php-vips/src/DebugLogger.php create mode 100644 src/wp-includes/php-vips/src/Direction.php create mode 100644 src/wp-includes/php-vips/src/Exception.php create mode 100644 src/wp-includes/php-vips/src/Extend.php create mode 100644 src/wp-includes/php-vips/src/FFI.php create mode 100644 src/wp-includes/php-vips/src/FailOn.php create mode 100644 src/wp-includes/php-vips/src/ForeignDzContainer.php create mode 100644 src/wp-includes/php-vips/src/ForeignDzDepth.php create mode 100644 src/wp-includes/php-vips/src/ForeignDzLayout.php create mode 100644 src/wp-includes/php-vips/src/ForeignHeifCompression.php create mode 100644 src/wp-includes/php-vips/src/ForeignHeifEncoder.php create mode 100644 src/wp-includes/php-vips/src/ForeignKeep.php create mode 100644 src/wp-includes/php-vips/src/ForeignPdfPageBox.php create mode 100644 src/wp-includes/php-vips/src/ForeignPngFilter.php create mode 100644 src/wp-includes/php-vips/src/ForeignPpmFormat.php create mode 100644 src/wp-includes/php-vips/src/ForeignSubsample.php create mode 100644 src/wp-includes/php-vips/src/ForeignTiffCompression.php create mode 100644 src/wp-includes/php-vips/src/ForeignTiffPredictor.php create mode 100644 src/wp-includes/php-vips/src/ForeignTiffResunit.php create mode 100644 src/wp-includes/php-vips/src/ForeignWebpPreset.php create mode 100644 src/wp-includes/php-vips/src/GObject.php create mode 100644 src/wp-includes/php-vips/src/GValue.php create mode 100644 src/wp-includes/php-vips/src/Image.php create mode 100644 src/wp-includes/php-vips/src/ImageAutodoc.php create mode 100644 src/wp-includes/php-vips/src/Intent.php create mode 100644 src/wp-includes/php-vips/src/Interesting.php create mode 100644 src/wp-includes/php-vips/src/Interpolate.php create mode 100644 src/wp-includes/php-vips/src/Interpretation.php create mode 100644 src/wp-includes/php-vips/src/Introspect.php create mode 100644 src/wp-includes/php-vips/src/Kernel.php create mode 100644 src/wp-includes/php-vips/src/OperationBoolean.php create mode 100644 src/wp-includes/php-vips/src/OperationComplex.php create mode 100644 src/wp-includes/php-vips/src/OperationComplex2.php create mode 100644 src/wp-includes/php-vips/src/OperationComplexget.php create mode 100644 src/wp-includes/php-vips/src/OperationMath.php create mode 100644 src/wp-includes/php-vips/src/OperationMath2.php create mode 100644 src/wp-includes/php-vips/src/OperationMorphology.php create mode 100644 src/wp-includes/php-vips/src/OperationRelational.php create mode 100644 src/wp-includes/php-vips/src/OperationRound.php create mode 100644 src/wp-includes/php-vips/src/PCS.php create mode 100644 src/wp-includes/php-vips/src/Precision.php create mode 100644 src/wp-includes/php-vips/src/RegionShrink.php create mode 100644 src/wp-includes/php-vips/src/SdfShape.php create mode 100644 src/wp-includes/php-vips/src/Size.php create mode 100644 src/wp-includes/php-vips/src/Source.php create mode 100644 src/wp-includes/php-vips/src/SourceCustom.php create mode 100644 src/wp-includes/php-vips/src/SourceResource.php create mode 100644 src/wp-includes/php-vips/src/Target.php create mode 100644 src/wp-includes/php-vips/src/TargetCustom.php create mode 100644 src/wp-includes/php-vips/src/TargetResource.php create mode 100644 src/wp-includes/php-vips/src/TextWrap.php create mode 100644 src/wp-includes/php-vips/src/Utils.php create mode 100644 src/wp-includes/php-vips/src/VipsObject.php create mode 100644 src/wp-includes/php-vips/src/VipsOperation.php create mode 100644 src/wp-includes/php-vips/third-party/Psr/Log/AbstractLogger.php create mode 100644 src/wp-includes/php-vips/third-party/Psr/Log/InvalidArgumentException.php create mode 100644 src/wp-includes/php-vips/third-party/Psr/Log/LICENSE create mode 100644 src/wp-includes/php-vips/third-party/Psr/Log/LogLevel.php create mode 100644 src/wp-includes/php-vips/third-party/Psr/Log/LoggerAwareInterface.php create mode 100644 src/wp-includes/php-vips/third-party/Psr/Log/LoggerAwareTrait.php create mode 100644 src/wp-includes/php-vips/third-party/Psr/Log/LoggerInterface.php create mode 100644 src/wp-includes/php-vips/third-party/Psr/Log/LoggerTrait.php create mode 100644 src/wp-includes/php-vips/third-party/Psr/Log/NullLogger.php create mode 100644 tools/php-vips/README.md create mode 100755 tools/php-vips/installer.sh create mode 100644 tools/php-vips/scoper.inc.php diff --git a/composer.json b/composer.json index 40a72ca0a8d29..9c69c82c514e5 100644 --- a/composer.json +++ b/composer.json @@ -46,8 +46,7 @@ "ext-xml": "*", "ext-xmlreader": "*", "ext-zip": "*", - "ext-zlib": "*", - "jcupitt/vips": "Required to use the optional WP_Image_Editor_Vips backend" + "ext-zlib": "*" }, "require-dev": { "composer/ca-bundle": "1.5.13", diff --git a/phpcs.xml.dist b/phpcs.xml.dist index 5a62c500f3150..9461da819186b 100644 --- a/phpcs.xml.dist +++ b/phpcs.xml.dist @@ -79,6 +79,7 @@ /src/wp-includes/PHPMailer/* /src/wp-includes/Requests/* /src/wp-includes/php-ai-client/* + /src/wp-includes/php-vips/* /src/wp-includes/SimplePie/* /src/wp-includes/sodium_compat/* /src/wp-includes/Text/* diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index 2425cdb37a1c3..040b31c109abb 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -6,6 +6,11 @@ * @subpackage Image_Editor */ +// The php-vips library is vendored in wp-includes/php-vips. +if ( ! class_exists( 'Jcupitt\Vips\Image' ) ) { + require_once ABSPATH . WPINC . '/php-vips/autoload.php'; +} + /** * WordPress Image Editor Class for Image Manipulation through VIPS * diff --git a/src/wp-includes/php-vips/LICENSE.txt b/src/wp-includes/php-vips/LICENSE.txt new file mode 100644 index 0000000000000..2f77dc583de83 --- /dev/null +++ b/src/wp-includes/php-vips/LICENSE.txt @@ -0,0 +1,20 @@ +Copyright (c) 2016 John Cupitt + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/src/wp-includes/php-vips/autoload.php b/src/wp-includes/php-vips/autoload.php new file mode 100644 index 0000000000000..bd5e8db0f558f --- /dev/null +++ b/src/wp-includes/php-vips/autoload.php @@ -0,0 +1,45 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * The Access enum. + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +abstract class Access +{ + const RANDOM = 'random'; + const SEQUENTIAL = 'sequential'; + const SEQUENTIAL_UNBUFFERED = 'sequential-unbuffered'; +} diff --git a/src/wp-includes/php-vips/src/Align.php b/src/wp-includes/php-vips/src/Align.php new file mode 100644 index 0000000000000..0bb4d1568372e --- /dev/null +++ b/src/wp-includes/php-vips/src/Align.php @@ -0,0 +1,54 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * The Align enum. + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +abstract class Align +{ + const LOW = 'low'; + const CENTRE = 'centre'; + const HIGH = 'high'; +} diff --git a/src/wp-includes/php-vips/src/Angle.php b/src/wp-includes/php-vips/src/Angle.php new file mode 100644 index 0000000000000..f7bce7289c7e1 --- /dev/null +++ b/src/wp-includes/php-vips/src/Angle.php @@ -0,0 +1,55 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * The Angle enum. + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +abstract class Angle +{ + const D0 = 'd0'; + const D90 = 'd90'; + const D180 = 'd180'; + const D270 = 'd270'; +} diff --git a/src/wp-includes/php-vips/src/Angle45.php b/src/wp-includes/php-vips/src/Angle45.php new file mode 100644 index 0000000000000..3d11e64718c8d --- /dev/null +++ b/src/wp-includes/php-vips/src/Angle45.php @@ -0,0 +1,59 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * The Angle45 enum. + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +abstract class Angle45 +{ + const D0 = 'd0'; + const D45 = 'd45'; + const D90 = 'd90'; + const D135 = 'd135'; + const D180 = 'd180'; + const D225 = 'd225'; + const D270 = 'd270'; + const D315 = 'd315'; +} diff --git a/src/wp-includes/php-vips/src/ArgumentFlags.php b/src/wp-includes/php-vips/src/ArgumentFlags.php new file mode 100644 index 0000000000000..5b0413a3e6b16 --- /dev/null +++ b/src/wp-includes/php-vips/src/ArgumentFlags.php @@ -0,0 +1,58 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * The ArgumentFlags enum. + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +abstract class ArgumentFlags +{ + const REQUIRED = 1; + const CONSTRUCT = 2; + const SET_ONCE = 4; + const SET_ALWAYS = 8; + const INPUT = 16; + const OUTPUT = 32; + const DEPRECATED = 64; + const MODIFY = 128; + const NAMES = ["REQUIRED" => self::REQUIRED, "CONSTRUCT" => self::CONSTRUCT, "SET_ONCE" => self::SET_ONCE, "SET_ALWAYS" => self::SET_ALWAYS, "INPUT" => self::INPUT, "OUTPUT" => self::OUTPUT, "DEPRECATED" => self::DEPRECATED, "MODIFY" => self::MODIFY]; +} diff --git a/src/wp-includes/php-vips/src/BandFormat.php b/src/wp-includes/php-vips/src/BandFormat.php new file mode 100644 index 0000000000000..fcef7943e9c27 --- /dev/null +++ b/src/wp-includes/php-vips/src/BandFormat.php @@ -0,0 +1,62 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * The BandFormat enum. + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +abstract class BandFormat +{ + const NOTSET = 'notset'; + const UCHAR = 'uchar'; + const CHAR = 'char'; + const USHORT = 'ushort'; + const SHORT = 'short'; + const UINT = 'uint'; + const INT = 'int'; + const FLOAT = 'float'; + const COMPLEX = 'complex'; + const DOUBLE = 'double'; + const DPCOMPLEX = 'dpcomplex'; +} diff --git a/src/wp-includes/php-vips/src/BlendMode.php b/src/wp-includes/php-vips/src/BlendMode.php new file mode 100644 index 0000000000000..f6f4f209253cf --- /dev/null +++ b/src/wp-includes/php-vips/src/BlendMode.php @@ -0,0 +1,76 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * The BlendMode enum. + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +abstract class BlendMode +{ + const CLEAR = 'clear'; + const SOURCE = 'source'; + const OVER = 'over'; + const IN = 'in'; + const OUT = 'out'; + const ATOP = 'atop'; + const DEST = 'dest'; + const DEST_OVER = 'dest-over'; + const DEST_IN = 'dest-in'; + const DEST_OUT = 'dest-out'; + const DEST_ATOP = 'dest-atop'; + const XOR1 = 'xor'; + const ADD = 'add'; + const SATURATE = 'saturate'; + const MULTIPLY = 'multiply'; + const SCREEN = 'screen'; + const OVERLAY = 'overlay'; + const DARKEN = 'darken'; + const LIGHTEN = 'lighten'; + const COLOUR_DODGE = 'colour-dodge'; + const COLOUR_BURN = 'colour-burn'; + const HARD_LIGHT = 'hard-light'; + const SOFT_LIGHT = 'soft-light'; + const DIFFERENCE = 'difference'; + const EXCLUSION = 'exclusion'; +} diff --git a/src/wp-includes/php-vips/src/Coding.php b/src/wp-includes/php-vips/src/Coding.php new file mode 100644 index 0000000000000..44097814ee7d6 --- /dev/null +++ b/src/wp-includes/php-vips/src/Coding.php @@ -0,0 +1,55 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * The Coding enum. + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +abstract class Coding +{ + const ERROR = 'error'; + const NONE = 'none'; + const LABQ = 'labq'; + const RAD = 'rad'; +} diff --git a/src/wp-includes/php-vips/src/Combine.php b/src/wp-includes/php-vips/src/Combine.php new file mode 100644 index 0000000000000..eafdb1c1fa30e --- /dev/null +++ b/src/wp-includes/php-vips/src/Combine.php @@ -0,0 +1,54 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * The Combine enum. + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +abstract class Combine +{ + const MAX = 'max'; + const SUM = 'sum'; + const MIN = 'min'; +} diff --git a/src/wp-includes/php-vips/src/CombineMode.php b/src/wp-includes/php-vips/src/CombineMode.php new file mode 100644 index 0000000000000..61686e63a7854 --- /dev/null +++ b/src/wp-includes/php-vips/src/CombineMode.php @@ -0,0 +1,53 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * The CombineMode enum. + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +abstract class CombineMode +{ + const SET = 'set'; + const ADD = 'add'; +} diff --git a/src/wp-includes/php-vips/src/CompassDirection.php b/src/wp-includes/php-vips/src/CompassDirection.php new file mode 100644 index 0000000000000..641e0287b3ca6 --- /dev/null +++ b/src/wp-includes/php-vips/src/CompassDirection.php @@ -0,0 +1,60 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * The CompassDirection enum. + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +abstract class CompassDirection +{ + const CENTRE = 'centre'; + const NORTH = 'north'; + const EAST = 'east'; + const SOUTH = 'south'; + const WEST = 'west'; + const NORTH_EAST = 'north-east'; + const SOUTH_EAST = 'south-east'; + const SOUTH_WEST = 'south-west'; + const NORTH_WEST = 'north-west'; +} diff --git a/src/wp-includes/php-vips/src/Config.php b/src/wp-includes/php-vips/src/Config.php new file mode 100644 index 0000000000000..de587f26861af --- /dev/null +++ b/src/wp-includes/php-vips/src/Config.php @@ -0,0 +1,160 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +use WordPress\VipsDependencies\Psr\Log\LoggerInterface; +/** + * This class contains the top-level libvips control methods. + * + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +class Config +{ + /** + * The logger instance. + */ + private static ?LoggerInterface $logger = null; + /** + * Sets a logger. This can be handy for debugging. For example: + * + * ```php + * Vips\Config::setLogger(new Vips\Logger); + * ``` + * + * @param LoggerInterface $logger + * + * @return void + */ + public static function setLogger(LoggerInterface $logger): void + { + self::$logger = $logger; + } + /** + * Gets a logger. + * + * @return LoggerInterface|null The logger or null. + */ + public static function getLogger(): ?LoggerInterface + { + return self::$logger; + } + /** + * Set the maximum number of operations to hold in the libvips operation + * cache. + * + * @param integer $value The maximum number of operations to cache. + * + * @return void + */ + public static function cacheSetMax(int $value): void + { + \Jcupitt\Vips\FFI::vips()->vips_cache_set_max($value); + } + /** + * Set the maximum amount of memory to allow cached operations to use, in + * bytes. + * + * @param integer $value The maximum amount of memory cached operations can + * hold, in bytes. + * + * @return void + */ + public static function cacheSetMaxMem(int $value): void + { + \Jcupitt\Vips\FFI::vips()->vips_cache_set_max_mem($value); + } + /** + * Set the maximum number of open files cached operations can use. + * + * @param integer $value The maximum number of open files cached operations + * can use. + * + * @return void + */ + public static function cacheSetMaxFiles(int $value): void + { + \Jcupitt\Vips\FFI::vips()->vips_cache_set_max_files($value); + } + /** + * Set the size of the pools of worker threads vips uses for image + * evaluation. + * + * @param integer $value The size of the pools of worker threads vips uses + * for image evaluation. + * + * @return void + */ + public static function concurrencySet(int $value): void + { + \Jcupitt\Vips\FFI::vips()->vips_concurrency_set($value); + } + /** + * Gets the libvips version number as a string of the form + * MAJOR.MINOR.MICRO, for example "8.6.1". + * + * @return string + */ + public static function version(): string + { + return \Jcupitt\Vips\FFI::version(); + } + /** + * Is this at least libvips major.minor[.patch]? + * @param int $x Major component. + * @param int $y Minor component. + * @param int $z Patch component. + * @return bool `true` if at least libvips major.minor[.patch]; otherwise, `false`. + */ + public static function atLeast(int $x, int $y, int $z = 0): bool + { + return \Jcupitt\Vips\FFI::atLeast($x, $y, $z); + } +} +/* + * Local variables: + * tab-width: 4 + * c-basic-offset: 4 + * End: + * vim600: expandtab sw=4 ts=4 fdm=marker + * vim<600: expandtab sw=4 ts=4 + */ diff --git a/src/wp-includes/php-vips/src/Connection.php b/src/wp-includes/php-vips/src/Connection.php new file mode 100644 index 0000000000000..22da4d0f72590 --- /dev/null +++ b/src/wp-includes/php-vips/src/Connection.php @@ -0,0 +1,33 @@ +pointer = \Jcupitt\Vips\FFI::vips()->cast(\Jcupitt\Vips\FFI::ctypes('VipsConnection'), $pointer); + parent::__construct($pointer); + } + /** + * Get the filename associated with a connection. Return null if there is no associated file. + */ + public function filename(): ?string + { + return \Jcupitt\Vips\FFI::vips()->vips_connection_filename($this->pointer); + } + /** + * Make a human-readable name for a connection suitable for error messages. + */ + public function nick(): ?string + { + return \Jcupitt\Vips\FFI::vips()->vips_connection_nick($this->pointer); + } +} diff --git a/src/wp-includes/php-vips/src/DebugLogger.php b/src/wp-includes/php-vips/src/DebugLogger.php new file mode 100644 index 0000000000000..b7533f541e930 --- /dev/null +++ b/src/wp-includes/php-vips/src/DebugLogger.php @@ -0,0 +1,87 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +use WordPress\VipsDependencies\Psr\Log\LoggerInterface; +use WordPress\VipsDependencies\Psr\Log\LoggerTrait; +const LOG_FORMAT = "[%datetime%] %level_name%: %message% %context%\n"; +const DATE_FORMAT = "Y-m-d\\TH:i:sP"; +/** + * A simple logger, handy for debugging. See Main::setLogger(). + * + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +class DebugLogger implements LoggerInterface +{ + // Use the LoggerTrait so that we only have to implement the generic + // log method. + use LoggerTrait; + /** + * Logs with an arbitrary level. + * + * @param mixed $level + * @param string $message + * @param array $context + * + * @return void + */ + public function log($level, $message, array $context = []): void + { + // `Vips\Image` to string convert + array_walk_recursive($context, function (&$value) { + if ($value instanceof \Jcupitt\Vips\Image) { + $value = (string) $value; + } + }); + $strParams = ['%datetime%' => date(DATE_FORMAT), '%level_name%' => $level, '%message%' => $message, '%context%' => json_encode($context, \JSON_UNESCAPED_SLASHES | \JSON_UNESCAPED_UNICODE | \JSON_PRESERVE_ZERO_FRACTION)]; + echo strtr(LOG_FORMAT, $strParams); + } +} +/* + * Local variables: + * tab-width: 4 + * c-basic-offset: 4 + * End: + * vim600: expandtab sw=4 ts=4 fdm=marker + * vim<600: expandtab sw=4 ts=4 + */ diff --git a/src/wp-includes/php-vips/src/Direction.php b/src/wp-includes/php-vips/src/Direction.php new file mode 100644 index 0000000000000..2d9e080bc053a --- /dev/null +++ b/src/wp-includes/php-vips/src/Direction.php @@ -0,0 +1,53 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * The Direction enum. + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +abstract class Direction +{ + const HORIZONTAL = 'horizontal'; + const VERTICAL = 'vertical'; +} diff --git a/src/wp-includes/php-vips/src/Exception.php b/src/wp-includes/php-vips/src/Exception.php new file mode 100644 index 0000000000000..70b7f0c382a80 --- /dev/null +++ b/src/wp-includes/php-vips/src/Exception.php @@ -0,0 +1,70 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * The vips exception class. All exceptions thrown by php-vips are subclasses + * of this. + * + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +class Exception extends \Exception +{ + public function __construct($message = "", $code = 0, ?\Throwable $previous = null) + { + if ($message == "") { + $message = "libvips error: " . \Jcupitt\Vips\FFI::vips()->vips_error_buffer(); + \Jcupitt\Vips\FFI::vips()->vips_error_clear(); + } + \Jcupitt\Vips\Utils::errorLog($message); + parent::__construct($message, $code, $previous); + } +} +/* + * Local variables: + * tab-width: 4 + * c-basic-offset: 4 + * End: + * vim600: expandtab sw=4 ts=4 fdm=marker + * vim<600: expandtab sw=4 ts=4 + */ diff --git a/src/wp-includes/php-vips/src/Extend.php b/src/wp-includes/php-vips/src/Extend.php new file mode 100644 index 0000000000000..2659692ab33b7 --- /dev/null +++ b/src/wp-includes/php-vips/src/Extend.php @@ -0,0 +1,57 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * The Extend enum. + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +abstract class Extend +{ + const BLACK = 'black'; + const COPY = 'copy'; + const REPEAT = 'repeat'; + const MIRROR = 'mirror'; + const WHITE = 'white'; + const BACKGROUND = 'background'; +} diff --git a/src/wp-includes/php-vips/src/FFI.php b/src/wp-includes/php-vips/src/FFI.php new file mode 100644 index 0000000000000..47813bd77beaf --- /dev/null +++ b/src/wp-includes/php-vips/src/FFI.php @@ -0,0 +1,766 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * This class contains the libvips FFI methods. + * + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +class FFI +{ + /** + * The FFI handle we use for the glib binary. + * + * @internal + */ + private static \FFI $glib; + /** + * The FFI handle we use for the gobject binary. + * + * @internal + */ + private static \FFI $gobject; + /** + * The FFI handle we use for the libvips binary. + * + * @internal + */ + private static \FFI $vips; + /** + * Are the above FFI handles initialized? + * + * @internal + */ + private static bool $ffi_inited = \false; + /** + * A list of paths where libvips might reside. + * + * @internal + */ + private static array $libraryPaths = [""]; + /** + * Look up these once. + * + * @internal + */ + private static array $ctypes; + private static array $gtypes; + private static array $ftypes; + /** + * The library version number we detect. + * + * @internal + */ + private static int $library_major; + private static int $library_minor; + private static int $library_micro; + public static function glib(): \FFI + { + self::init(); + return self::$glib; + } + public static function gobject(): \FFI + { + self::init(); + return self::$gobject; + } + public static function vips(): \FFI + { + self::init(); + return self::$vips; + } + public static function ctypes(string $name): \FFI\CType + { + self::init(); + return self::$ctypes[$name]; + } + public static function gtypes(string $name): int + { + self::init(); + return self::$gtypes[$name]; + } + public static function ftypes(string $name): string + { + self::init(); + return self::$ftypes[$name]; + } + /** + * Gets the libvips version number as a string of the form + * MAJOR.MINOR.MICRO, for example "8.6.1". + * + * @return string + */ + public static function version(): string + { + self::init(); + return self::$library_major . "." . self::$library_minor . "." . self::$library_micro; + } + /** + * Is this at least libvips major.minor[.patch]? + * @param int $x Major component. + * @param int $y Minor component. + * @param int $z Patch component. + * @return bool `true` if at least libvips major.minor[.patch]; otherwise, `false`. + */ + public static function atLeast(int $x, int $y, int $z = 0): bool + { + return self::$library_major > $x || self::$library_major === $x && self::$library_minor > $y || self::$library_major === $x && self::$library_minor === $y && self::$library_micro >= $z; + } + /** + * Adds a directory to the search path for shared libraries. + * + * This method has no effect if FFI handles are already initialized, + * if the specified path is non-existent, or if the path is already + * included. + * + * @param string $path The path of the library. + * @return bool `true` if the path was added; otherwise, `false`. + */ + public static function addLibraryPath(string $path): bool + { + // Already initialized. + if (self::$ffi_inited) { + return \false; + } + $path = realpath($path); + if ($path === \false) { + return \false; + } + $path .= \DIRECTORY_SEPARATOR; + if (in_array($path, self::$libraryPaths)) { + return \false; + } + self::$libraryPaths[] = $path; + return \true; + } + /** + * Shut down libvips. Call this just before process exit. + * + * @return void + */ + public static function shutDown(): void + { + self::vips()->vips_shutdown(); + } + public static function newGClosure(): \FFI\CData + { + // GClosure measures 32-bit with the first few fields until marshal. + // - Marshal is a function pointer, thus platform-dependant. + // - Data is a pointer, thus platform-dependant. + // - Notifiers is an array-pointer, thus platform-dependant. + // All in all it's basically 4 (bytes) + 3 * POINTER_SIZE + // However, gobject wants 8 (bytes) + 3 * POINTER_SIZE. + // I'm not sure where that extra byte comes from. Padding on 64-bit machines? + return self::gobject()->g_closure_new_simple(8 + 3 * \PHP_INT_SIZE, null); + } + private static function libraryName(string $name, int $abi): string + { + switch (\PHP_OS_FAMILY) { + case "Windows": + return "{$name}-{$abi}.dll"; + case "OSX": + case "Darwin": + return "{$name}.{$abi}.dylib"; + default: + // most *nix + return "{$name}.so.{$abi}"; + } + } + private static function libraryLoad(string $libraryName, string $interface): ?\FFI + { + \Jcupitt\Vips\Utils::debugLog("trying to open", ["libraryName" => $libraryName]); + foreach (self::$libraryPaths as $path) { + \Jcupitt\Vips\Utils::debugLog("trying path", ["path" => $path]); + try { + $library = \FFI::cdef($interface, $path . $libraryName); + \Jcupitt\Vips\Utils::debugLog("success", []); + return $library; + } catch (\FFI\Exception $e) { + \Jcupitt\Vips\Utils::debugLog("init", ["msg" => "library load failed", "exception" => $e->getMessage()]); + } + } + return null; + } + private static function init(): void + { + // Already initialized. + if (self::$ffi_inited) { + return; + } + // detect the most common installation problems + if (!extension_loaded('ffi')) { + throw new \Jcupitt\Vips\Exception('FFI extension not loaded'); + } + if (!ini_get('ffi.enable')) { + throw new \Jcupitt\Vips\Exception("ffi.enable not set to 'true'"); + } + $vips_libname = self::libraryName("libvips", 42); + $glib_libname = self::libraryName("libglib-2.0", 0); + $gobject_libname = self::libraryName("libgobject-2.0", 0); + \Jcupitt\Vips\Utils::debugLog("init", ["library" => $vips_libname]); + $is_64bits = \PHP_INT_SIZE === 8; + if (\PHP_OS_FAMILY === "OSX" || \PHP_OS_FAMILY === "Darwin") { + // Homebrew on Apple Silicon + self::addLibraryPath("/opt/homebrew/lib"); + // See https://github.com/Homebrew/brew/issues/13481#issuecomment-1207203483 + self::addLibraryPath("/usr/local/lib"); + } + $vips = self::libraryLoad($vips_libname, <<<'CPP' + int vips_init (const char *argv0); + const char *vips_error_buffer (void); + int vips_version(int flag); +CPP +); + if ($vips === null) { + // drop the "" (system path) member + array_shift(self::$libraryPaths); + $msg = "Unable to open library '{$vips_libname}'"; + if (!empty(self::$libraryPaths)) { + $msg .= " in any of ['" . implode("', '", self::$libraryPaths) . "']"; + } + $msg .= ". Make sure that you've installed libvips and that '{$vips_libname}'"; + $msg .= " is on your system's library search path."; + throw new \Jcupitt\Vips\Exception($msg); + } + $result = $vips->vips_init(""); + if ($result != 0) { + throw new \Jcupitt\Vips\Exception("libvips error: " . $vips->vips_error_buffer()); + } + \Jcupitt\Vips\Utils::debugLog("init", ["vips_init" => $result]); + # get the library version number, then we can build the API + self::$library_major = $vips->vips_version(0); + self::$library_minor = $vips->vips_version(1); + self::$library_micro = $vips->vips_version(2); + \Jcupitt\Vips\Utils::debugLog("init", ["libvips version" => [self::$library_major, self::$library_minor, self::$library_micro]]); + if (!self::atLeast(8, 7)) { + throw new \Jcupitt\Vips\Exception("your libvips is too old -- " . "8.7 or later required"); + } + // Typedefs shared across the libvips, GLib and GObject declarations + $typedefs = <<<'CPP' +// we need the glib names for these types +typedef uint32_t guint32; +typedef int32_t gint32; +typedef uint64_t guint64; +typedef int64_t gint64; +typedef void* gpointer; + +CPP; + // GType is the size of a pointer + $typedefs .= 'typedef ' . ($is_64bits ? 'guint64' : 'guint32') . ' GType;'; + $typedefs .= <<<'CPP' + +typedef struct _GData GData; + +typedef struct _GTypeClass GTypeClass; + +typedef struct _GTypeInstance { + GTypeClass *g_class; +} GTypeInstance; + +typedef struct _GObject { + GTypeInstance g_type_instance; + unsigned int ref_count; + GData *qdata; +} GObject; +CPP; + // GLib declarations + $glib_decls = $typedefs . <<<'CPP' +void* g_malloc (size_t size); +void g_free (void* data); +void g_strfreev (char** str_array); +CPP; + // GObject declarations + $gobject_decls = $typedefs . <<<'CPP' +typedef struct _GValue { + GType g_type; + guint64 data[2]; +} GValue; + +typedef struct _GParamSpec { + GTypeInstance g_type_instance; + + const char* name; + unsigned int flags; + GType value_type; + GType owner_type; + + // private, but cffi in API mode needs these to be able to get the + // offset of any member + char* _nick; + char* _blurb; + GData* qdata; + unsigned int ref_count; + unsigned int param_id; +} GParamSpec; + +const char* g_type_name (GType gtype); +GType g_type_from_name (const char* name); + +void g_value_init (GValue* value, GType gtype); +void g_value_unset (GValue* value); +GType g_type_fundamental (GType gtype); + +void g_value_set_boolean (GValue* value, bool v_boolean); +void g_value_set_int (GValue* value, int i); +void g_value_set_uint64 (GValue* value, guint64 ull); +void g_value_set_int64 (GValue* value, guint64 ull); +void g_value_set_double (GValue* value, double d); +void g_value_set_enum (GValue* value, int e); +void g_value_set_flags (GValue* value, unsigned int f); +void g_value_set_string (GValue* value, const char* str); +void g_value_set_object (GValue* value, void* object); +void g_value_set_pointer (GValue* value, gpointer pointer); + +bool g_value_get_boolean (const GValue* value); +int g_value_get_int (GValue* value); +guint64 g_value_get_uint64 (GValue* value); +gint64 g_value_get_int64 (GValue* value); +double g_value_get_double (GValue* value); +int g_value_get_enum (GValue* value); +unsigned int g_value_get_flags (GValue* value); +const char* g_value_get_string (GValue* value); +void* g_value_get_object (GValue* value); +gpointer g_value_get_pointer (GValue* value); + +typedef struct _GEnumValue { + int value; + + const char *value_name; + const char *value_nick; +} GEnumValue; + +typedef struct _GEnumClass { + GTypeClass *g_type_class; + + int minimum; + int maximum; + unsigned int n_values; + GEnumValue *values; +} GEnumClass; + +typedef struct _GFlagsValue { + unsigned int value; + + const char *value_name; + const char *value_nick; +} GFlagsValue; + +typedef struct _GFlagsClass { + GTypeClass *g_type_class; + + unsigned int mask; + unsigned int n_values; + GFlagsValue *values; +} GFlagsClass; + +void* g_type_class_ref (GType type); + +void* g_object_new (GType type, void*); +void g_object_ref (void* object); +void g_object_unref (void* object); + +void g_object_set_property (GObject* object, + const char *name, GValue* value); +void g_object_get_property (GObject* object, + const char* name, GValue* value); + +typedef void (*GCallback)(void); +typedef void (*GClosureNotify)(void* data, struct _GClosure *); +long g_signal_connect_data (GObject* object, + const char* detailed_signal, + GCallback c_handler, + void* data, + GClosureNotify destroy_data, + int connect_flags); + +const char* g_param_spec_get_blurb (GParamSpec* psp); + +typedef void *GClosure; +typedef void (*marshaler)( + struct GClosure* closure, + GValue* return_value, + int n_param_values, + const GValue* param_values, + void* invocation_hint, + void* marshal_data +); +void g_closure_set_marshal(GClosure* closure, marshaler marshal); +long g_signal_connect_closure(GObject* object, const char* detailed_signal, GClosure *closure, bool after); +GClosure* g_closure_new_simple (int sizeof_closure, void* data); +CPP; + # the whole libvips API, mostly adapted from pyvips + $vips_decls = $typedefs . <<<'CPP' +typedef struct _VipsImage VipsImage; +typedef struct _VipsProgress VipsProgress; + +// Defined in GObject, just typedef to void +typedef void GParamSpec; +typedef void GValue; + +int vips_init (const char *argv0); +int vips_shutdown (void); + +const char *vips_error_buffer (void); +void vips_error_clear (void); +void vips_error_freeze (void); +void vips_error_thaw (void); + +int vips_version(int flag); + +void vips_leak_set (int leak); + +GType vips_type_find (const char* basename, const char* nickname); +const char* vips_nickname_find (GType type); + +typedef void* (*VipsTypeMap2Fn) (GType type, void* a, void* b); +void* vips_type_map (GType base, VipsTypeMap2Fn fn, void* a, void* b); + +int vips_enum_from_nick (const char* domain, + GType gtype, const char* str); +const char *vips_enum_nick (GType gtype, int value); + +void vips_value_set_ref_string (GValue* value, const char* str); +void vips_value_set_array_double (GValue* value, +const double* array, int n ); +void vips_value_set_array_int (GValue* value, +const int* array, int n ); +void vips_value_set_array_image (GValue *value, int n); +typedef void (*FreeFn)(void* a); +void vips_value_set_blob (GValue* value, + FreeFn free_fn, void* data, size_t length); +void* vips_blob_copy (const void *data, size_t length); +void vips_area_unref (void *area); + +const char* vips_value_get_ref_string (const GValue* value, + size_t* length); +double* vips_value_get_array_double (const GValue* value, int* n); +int* vips_value_get_array_int (const GValue* value, int* n); +VipsImage** vips_value_get_array_image (const GValue* value, int* n); +void* vips_value_get_blob (const GValue* value, size_t* length); + +// need to make some of these by hand +GType vips_interpretation_get_type (void); +GType vips_operation_flags_get_type (void); +GType vips_band_format_get_type (void); + +void vips_image_set_progress (VipsImage* image, bool progress); +void vips_image_set_kill (VipsImage* image, bool kill); + +typedef struct _VipsProgress { + VipsImage* im; + + int run; + int eta; + gint64 tpels; + gint64 npels; + int percent; + void* start; +} VipsProgress; + +typedef struct _VipsObject { + GObject parent_instance; + + bool constructed; + bool static_object; + void *argument_table; + char *nickname; + char *description; + bool preclose; + bool close; + bool postclose; + size_t local_memory; +} VipsObject; + +typedef struct _VipsObjectClass VipsObjectClass; + +typedef struct _VipsArgument { + GParamSpec *pspec; +} VipsArgument; + +typedef struct _VipsArgumentInstance { + VipsArgument parent; + + // more +} VipsArgumentInstance; + +typedef enum _VipsArgumentFlags { + VIPS_ARGUMENT_NONE = 0, + VIPS_ARGUMENT_REQUIRED = 1, + VIPS_ARGUMENT_CONSTRUCT = 2, + VIPS_ARGUMENT_SET_ONCE = 4, + VIPS_ARGUMENT_SET_ALWAYS = 8, + VIPS_ARGUMENT_INPUT = 16, + VIPS_ARGUMENT_OUTPUT = 32, + VIPS_ARGUMENT_DEPRECATED = 64, + VIPS_ARGUMENT_MODIFY = 128 +} VipsArgumentFlags; + +typedef struct _VipsArgumentClass { + VipsArgument parent; + + VipsObjectClass *object_class; + VipsArgumentFlags flags; + int priority; + unsigned int offset; +} VipsArgumentClass; + +int vips_object_get_argument (VipsObject* object, const char *name, + GParamSpec** pspec, + VipsArgumentClass** argument_class, + VipsArgumentInstance** argument_instance); + +void vips_object_print_all (void); + +int vips_object_set_from_string (VipsObject* object, + const char* options); + +const char* vips_object_get_description (VipsObject* object); + +typedef struct _VipsImage { + VipsObject parent_instance; + // more +} VipsImage; + +const char* vips_foreign_find_load (const char* name); +const char* vips_foreign_find_load_buffer (const void* data, + size_t size); +const char* vips_foreign_find_save (const char* name); +const char* vips_foreign_find_save_buffer (const char* suffix); + +VipsImage* vips_image_new_matrix_from_array (int width, int height, + const double* array, int size); +VipsImage* vips_image_new_from_memory (const void* data, size_t size, + int width, int height, int bands, int format); +VipsImage* vips_image_new_from_memory_copy (const void *data, size_t size, + int width, int height, int bands, int format); + +VipsImage* vips_image_copy_memory (VipsImage* image); + +GType vips_image_get_typeof (const VipsImage* image, + const char* name); +int vips_image_get (const VipsImage* image, + const char* name, GValue* value_copy); +void vips_image_set (VipsImage* image, + const char* name, GValue* value); +int vips_image_remove (VipsImage* image, const char* name); + +char* vips_filename_get_filename (const char* vips_filename); +char* vips_filename_get_options (const char* vips_filename); + +VipsImage* vips_image_new_temp_file (const char* format); + +int vips_image_write (VipsImage* image, VipsImage* out); +void* vips_image_write_to_memory (VipsImage* in, size_t* size_out); + +typedef struct _VipsInterpolate { + VipsObject parent_object; + + // more +} VipsInterpolate; + +VipsInterpolate* vips_interpolate_new (const char* name); + +typedef struct _VipsOperation { + VipsObject parent_instance; + + // more +} VipsOperation; + +VipsOperation* vips_operation_new (const char* name); + +typedef void* (*VipsArgumentMapFn) (VipsObject* object, + GParamSpec* pspec, + VipsArgumentClass* argument_class, + VipsArgumentInstance* argument_instance, + void* a, void* b); + +void* vips_argument_map (VipsObject* object, + VipsArgumentMapFn fn, void* a, void* b); + +typedef struct _VipsRegion { + VipsObject parent_object; + + // more +} VipsRegion; +VipsRegion* vips_region_new (VipsImage*); + +VipsOperation* vips_cache_operation_build (VipsOperation* operation); +void vips_object_unref_outputs (VipsObject* object); + +int vips_operation_get_flags (VipsOperation* operation); + +void vips_concurrency_set( int concurrency ); + +void vips_cache_set_max (int max); +void vips_cache_set_max_mem (size_t max_mem); +void vips_cache_set_max_files (int max_files); +void vips_cache_set_trace (int trace); + +int vips_cache_get_max(); +int vips_cache_get_size(); +size_t vips_cache_get_max_mem(); +int vips_cache_get_max_files(); + +size_t vips_tracked_get_mem_highwater(); +size_t vips_tracked_get_mem(); +int vips_tracked_get_allocs(); +int vips_tracked_get_files(); + +char** vips_image_get_fields (VipsImage* image); +int vips_image_hasalpha (VipsImage* image); + +GType vips_blend_mode_get_type (void); +void vips_value_set_blob_free (GValue* value, void* data, size_t length); + +int vips_object_get_args (VipsObject* object, + const char*** names, int** flags, int* n_args); +CPP; + if (self::atLeast(8, 8)) { + $vips_decls = $vips_decls . <<<'CPP' +char** vips_foreign_get_suffixes (void); + +void* vips_region_fetch (VipsRegion*, int, int, int, int, + size_t* length); +int vips_region_width (VipsRegion*); +int vips_region_height (VipsRegion*); +int vips_image_get_page_height (VipsImage*); +int vips_image_get_n_pages (VipsImage*); +CPP; + } + if (self::atLeast(8, 8)) { + $vips_decls = $vips_decls . <<<'CPP' +typedef struct _VipsConnection { + VipsObject parent_object; + + // more +} VipsConnection; + +const char* vips_connection_filename (VipsConnection* stream); +const char* vips_connection_nick (VipsConnection* stream); + +typedef struct _VipsSource { + VipsConnection parent_object; + + // more +} VipsSource; + +VipsSource* vips_source_new_from_descriptor (int descriptor); +VipsSource* vips_source_new_from_file (const char* filename); +VipsSource* vips_source_new_from_blob (void* blob); + +typedef struct _VipsSourceCustom { + VipsSource parent_object; + + // more +} VipsSourceCustom; + +VipsSourceCustom* vips_source_custom_new (void); + +typedef struct _VipsTarget { + VipsConnection parent_object; + + // more +} VipsTarget; + +VipsTarget* vips_target_new_to_descriptor (int descriptor); +VipsTarget* vips_target_new_to_file (const char* filename); +VipsTarget* vips_target_new_to_memory (void); + +typedef struct _VipsTargetCustom { + VipsTarget parent_object; + + // more +} VipsTargetCustom; + +VipsTargetCustom* vips_target_custom_new (void); + +const char* vips_foreign_find_load_source (VipsSource *source); +const char* vips_foreign_find_save_target (const char* suffix); +CPP; + } + if (self::atLeast(8, 18)) { + $vips_decls = $vips_decls . <<<'CPP' +VipsImage* vips_image_get_gainmap(const VipsImage* image); +CPP; + } + \Jcupitt\Vips\Utils::debugLog("init", ["binding ..."]); + /** + * We can sometimes get dependent libraries from libvips -- either the platform + * will open dependencies for us automatically, or the libvips binary has been + * built to includes all main dependencies (common on Windows, can happen + * elsewhere). + * + * We must get GLib functions from libvips if we can, since it will be the + * one that libvips itself is using, and they will share runtime types. + */ + self::$glib = self::libraryLoad($vips_libname, $glib_decls) ?? self::libraryLoad($glib_libname, $glib_decls); + self::$gobject = self::libraryLoad($vips_libname, $gobject_decls) ?? self::libraryLoad($gobject_libname, $gobject_decls); + self::$vips = self::libraryLoad($vips_libname, $vips_decls); + # Useful for debugging + # self::$vips->vips_leak_set(1); + # force the creation of some types we need + self::$vips->vips_blend_mode_get_type(); + self::$vips->vips_interpretation_get_type(); + self::$vips->vips_operation_flags_get_type(); + self::$vips->vips_band_format_get_type(); + // look these up in advance + self::$ctypes = ["GObject" => self::$gobject->type("GObject*"), "GClosure" => self::$gobject->type("GClosure"), "GParamSpec" => self::$gobject->type("GParamSpec*"), "VipsObject" => self::$vips->type("VipsObject*"), "VipsOperation" => self::$vips->type("VipsOperation*"), "VipsImage" => self::$vips->type("VipsImage*"), "VipsInterpolate" => self::$vips->type("VipsInterpolate*"), "VipsProgress" => self::$vips->type("VipsProgress*")]; + if (self::atLeast(8, 9)) { + self::$ctypes = array_merge(self::$ctypes, ["VipsConnection" => self::$vips->type("VipsConnection*"), "VipsSource" => self::$vips->type("VipsSource*"), "VipsSourceCustom" => self::$vips->type("VipsSourceCustom*"), "VipsTarget" => self::$vips->type("VipsTarget*"), "VipsTargetCustom" => self::$vips->type("VipsTargetCustom*")]); + } + self::$gtypes = ["gboolean" => self::$gobject->g_type_from_name("gboolean"), "gint" => self::$gobject->g_type_from_name("gint"), "gint64" => self::$gobject->g_type_from_name("gint64"), "guint64" => self::$gobject->g_type_from_name("guint64"), "gdouble" => self::$gobject->g_type_from_name("gdouble"), "gchararray" => self::$gobject->g_type_from_name("gchararray"), "VipsRefString" => self::$gobject->g_type_from_name("VipsRefString"), "GEnum" => self::$gobject->g_type_from_name("GEnum"), "GFlags" => self::$gobject->g_type_from_name("GFlags"), "VipsBandFormat" => self::$gobject->g_type_from_name("VipsBandFormat"), "VipsBlendMode" => self::$gobject->g_type_from_name("VipsBlendMode"), "VipsArrayInt" => self::$gobject->g_type_from_name("VipsArrayInt"), "VipsArrayDouble" => self::$gobject->g_type_from_name("VipsArrayDouble"), "VipsArrayImage" => self::$gobject->g_type_from_name("VipsArrayImage"), "VipsBlob" => self::$gobject->g_type_from_name("VipsBlob"), "GObject" => self::$gobject->g_type_from_name("GObject"), "VipsImage" => self::$gobject->g_type_from_name("VipsImage"), "GClosure" => self::$gobject->g_type_from_name("GClosure")]; + // map vips format names to c type names + self::$ftypes = ["char" => "char", "uchar" => "unsigned char", "short" => "short", "ushort" => "unsigned short", "int" => "int", "uint" => "unsigned int", "float" => "float", "double" => "double", "complex" => "float", "dpcomplex" => "double"]; + \Jcupitt\Vips\Utils::debugLog("init", ["done"]); + self::$ffi_inited = \true; + } +} +/* + * Local variables: + * tab-width: 4 + * c-basic-offset: 4 + * End: + * vim600: expandtab sw=4 ts=4 fdm=marker + * vim<600: expandtab sw=4 ts=4 + */ diff --git a/src/wp-includes/php-vips/src/FailOn.php b/src/wp-includes/php-vips/src/FailOn.php new file mode 100644 index 0000000000000..6fb9b28e902b0 --- /dev/null +++ b/src/wp-includes/php-vips/src/FailOn.php @@ -0,0 +1,55 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * The FailOn enum. + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +abstract class FailOn +{ + const NONE = 'none'; + const TRUNCATED = 'truncated'; + const ERROR = 'error'; + const WARNING = 'warning'; +} diff --git a/src/wp-includes/php-vips/src/ForeignDzContainer.php b/src/wp-includes/php-vips/src/ForeignDzContainer.php new file mode 100644 index 0000000000000..1a28125ce96d4 --- /dev/null +++ b/src/wp-includes/php-vips/src/ForeignDzContainer.php @@ -0,0 +1,54 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * The ForeignDzContainer enum. + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +abstract class ForeignDzContainer +{ + const FS = 'fs'; + const ZIP = 'zip'; + const SZI = 'szi'; +} diff --git a/src/wp-includes/php-vips/src/ForeignDzDepth.php b/src/wp-includes/php-vips/src/ForeignDzDepth.php new file mode 100644 index 0000000000000..cdb02aec9ea68 --- /dev/null +++ b/src/wp-includes/php-vips/src/ForeignDzDepth.php @@ -0,0 +1,54 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * The ForeignDzDepth enum. + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +abstract class ForeignDzDepth +{ + const ONEPIXEL = 'onepixel'; + const ONETILE = 'onetile'; + const ONE = 'one'; +} diff --git a/src/wp-includes/php-vips/src/ForeignDzLayout.php b/src/wp-includes/php-vips/src/ForeignDzLayout.php new file mode 100644 index 0000000000000..d0006523b949b --- /dev/null +++ b/src/wp-includes/php-vips/src/ForeignDzLayout.php @@ -0,0 +1,56 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * The ForeignDzLayout enum. + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +abstract class ForeignDzLayout +{ + const DZ = 'dz'; + const ZOOMIFY = 'zoomify'; + const GOOGLE = 'google'; + const IIIF = 'iiif'; + const IIIF3 = 'iiif3'; +} diff --git a/src/wp-includes/php-vips/src/ForeignHeifCompression.php b/src/wp-includes/php-vips/src/ForeignHeifCompression.php new file mode 100644 index 0000000000000..b482400105207 --- /dev/null +++ b/src/wp-includes/php-vips/src/ForeignHeifCompression.php @@ -0,0 +1,55 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * The ForeignHeifCompression enum. + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +abstract class ForeignHeifCompression +{ + const HEVC = 'hevc'; + const AVC = 'avc'; + const JPEG = 'jpeg'; + const AV1 = 'av1'; +} diff --git a/src/wp-includes/php-vips/src/ForeignHeifEncoder.php b/src/wp-includes/php-vips/src/ForeignHeifEncoder.php new file mode 100644 index 0000000000000..f2ba78e9ea7c2 --- /dev/null +++ b/src/wp-includes/php-vips/src/ForeignHeifEncoder.php @@ -0,0 +1,56 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * The ForeignHeifEncoder enum. + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +abstract class ForeignHeifEncoder +{ + const AUTO = 'auto'; + const AOM = 'aom'; + const RAV1E = 'rav1e'; + const SVT = 'svt'; + const X265 = 'x265'; +} diff --git a/src/wp-includes/php-vips/src/ForeignKeep.php b/src/wp-includes/php-vips/src/ForeignKeep.php new file mode 100644 index 0000000000000..648c0a9afccd8 --- /dev/null +++ b/src/wp-includes/php-vips/src/ForeignKeep.php @@ -0,0 +1,59 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * The ForeignKeep flags. + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +abstract class ForeignKeep +{ + const NONE = 0; + const EXIF = 1; + const XMP = 2; + const IPTC = 4; + const ICC = 8; + const OTHER = 16; + const GAINMAP = 32; + const ALL = 63; +} diff --git a/src/wp-includes/php-vips/src/ForeignPdfPageBox.php b/src/wp-includes/php-vips/src/ForeignPdfPageBox.php new file mode 100644 index 0000000000000..d82b053fa24a9 --- /dev/null +++ b/src/wp-includes/php-vips/src/ForeignPdfPageBox.php @@ -0,0 +1,56 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * The ForeignPdfPageBox enum. + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +abstract class ForeignPdfPageBox +{ + const MEDIA = 'media'; + const CROP = 'crop'; + const TRIM = 'trim'; + const BLEED = 'bleed'; + const ART = 'art'; +} diff --git a/src/wp-includes/php-vips/src/ForeignPngFilter.php b/src/wp-includes/php-vips/src/ForeignPngFilter.php new file mode 100644 index 0000000000000..ea521bddb819a --- /dev/null +++ b/src/wp-includes/php-vips/src/ForeignPngFilter.php @@ -0,0 +1,57 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * The ForeignPngFilter flags. + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +abstract class ForeignPngFilter +{ + const NONE = 8; + const SUB = 16; + const UP = 32; + const AVG = 64; + const PAETH = 128; + const ALL = 248; +} diff --git a/src/wp-includes/php-vips/src/ForeignPpmFormat.php b/src/wp-includes/php-vips/src/ForeignPpmFormat.php new file mode 100644 index 0000000000000..9ec75a8af91a4 --- /dev/null +++ b/src/wp-includes/php-vips/src/ForeignPpmFormat.php @@ -0,0 +1,56 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * The ForeignPpmFormat enum. + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +abstract class ForeignPpmFormat +{ + const PBM = 'pbm'; + const PGM = 'pgm'; + const PPM = 'ppm'; + const PFM = 'pfm'; + const PNM = 'pnm'; +} diff --git a/src/wp-includes/php-vips/src/ForeignSubsample.php b/src/wp-includes/php-vips/src/ForeignSubsample.php new file mode 100644 index 0000000000000..e7cb6e56bc77c --- /dev/null +++ b/src/wp-includes/php-vips/src/ForeignSubsample.php @@ -0,0 +1,54 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * The ForeignSubsample enum. + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +abstract class ForeignSubsample +{ + const AUTO = 'auto'; + const ON = 'on'; + const OFF = 'off'; +} diff --git a/src/wp-includes/php-vips/src/ForeignTiffCompression.php b/src/wp-includes/php-vips/src/ForeignTiffCompression.php new file mode 100644 index 0000000000000..b9670ed79c3ca --- /dev/null +++ b/src/wp-includes/php-vips/src/ForeignTiffCompression.php @@ -0,0 +1,60 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * The ForeignTiffCompression enum. + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +abstract class ForeignTiffCompression +{ + const NONE = 'none'; + const JPEG = 'jpeg'; + const DEFLATE = 'deflate'; + const PACKBITS = 'packbits'; + const CCITTFAX4 = 'ccittfax4'; + const LZW = 'lzw'; + const WEBP = 'webp'; + const ZSTD = 'zstd'; + const JP2K = 'jp2k'; +} diff --git a/src/wp-includes/php-vips/src/ForeignTiffPredictor.php b/src/wp-includes/php-vips/src/ForeignTiffPredictor.php new file mode 100644 index 0000000000000..b337e263901c4 --- /dev/null +++ b/src/wp-includes/php-vips/src/ForeignTiffPredictor.php @@ -0,0 +1,54 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * The ForeignTiffPredictor enum. + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +abstract class ForeignTiffPredictor +{ + const NONE = 'none'; + const HORIZONTAL = 'horizontal'; + const FLOAT = 'float'; +} diff --git a/src/wp-includes/php-vips/src/ForeignTiffResunit.php b/src/wp-includes/php-vips/src/ForeignTiffResunit.php new file mode 100644 index 0000000000000..a0f2122028aa4 --- /dev/null +++ b/src/wp-includes/php-vips/src/ForeignTiffResunit.php @@ -0,0 +1,53 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * The ForeignTiffResunit enum. + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +abstract class ForeignTiffResunit +{ + const CM = 'cm'; + const INCH = 'inch'; +} diff --git a/src/wp-includes/php-vips/src/ForeignWebpPreset.php b/src/wp-includes/php-vips/src/ForeignWebpPreset.php new file mode 100644 index 0000000000000..2457162c1fb40 --- /dev/null +++ b/src/wp-includes/php-vips/src/ForeignWebpPreset.php @@ -0,0 +1,57 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * The ForeignWebpPreset enum. + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +abstract class ForeignWebpPreset +{ + const DEFAULT1 = 'default'; + const PICTURE = 'picture'; + const PHOTO = 'photo'; + const DRAWING = 'drawing'; + const ICON = 'icon'; + const TEXT = 'text'; +} diff --git a/src/wp-includes/php-vips/src/GObject.php b/src/wp-includes/php-vips/src/GObject.php new file mode 100644 index 0000000000000..b4635e82fb2ff --- /dev/null +++ b/src/wp-includes/php-vips/src/GObject.php @@ -0,0 +1,219 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/libvips/php-vips + */ +namespace Jcupitt\Vips; + +use Closure; +use FFI\CData; +/** + * This class holds a pointer to a GObject and manages object lifetime. + * + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/libvips/php-vips + */ +abstract class GObject +{ + /** + * A pointer to the underlying GObject. + * + * @internal + */ + private CData $pointer; + /** + * libvips executes FFI callbacks off the main thread and this confuses + * the stack limit checks available since PHP 8.3.0. We need to check + * if `zend.max_allowed_stack_size` is set to `-1`. + * See: https://github.com/libvips/php-vips/pull/237. + */ + private static bool $check_max_stack_size = \true; + /** + * Wrap a GObject around an underlying vips resource. The GObject takes + * ownership of the pointer and will unref it on finalize. + * + * Don't call this yourself, users should stick to (for example) + * Image::newFromFile(). + * + * @param CData $pointer The underlying pointer that this + * object should wrap. + * + * @internal + */ + public function __construct(CData $pointer) + { + $this->pointer = \Jcupitt\Vips\FFI::vips()->cast(\Jcupitt\Vips\FFI::ctypes("GObject"), $pointer); + } + public function __destruct() + { + $this->unref(); + } + public function __clone() + { + $this->ref(); + } + public function ref(): void + { + \Jcupitt\Vips\FFI::gobject()->g_object_ref($this->pointer); + } + public function unref(): void + { + \Jcupitt\Vips\FFI::gobject()->g_object_unref($this->pointer); + } + /** + * Connect to a signal on this object. + * The callback will be triggered every time this signal is issued on this instance. + * @throws Exception + */ + public function signalConnect(string $name, callable $callback): void + { + if (self::$check_max_stack_size) { + $max_allowed_stack_size = ini_get('zend.max_allowed_stack_size'); + if ($max_allowed_stack_size !== \false && $max_allowed_stack_size !== '-1') { + throw new \Jcupitt\Vips\Exception("signalConnect() requires zend.max_allowed_stack_size set to '-1'"); + } + self::$check_max_stack_size = \false; + } + $marshaler = self::getMarshaler($name, $callback); + if ($marshaler === null) { + throw new \Jcupitt\Vips\Exception("unsupported signal {$name}"); + } + $gc = \Jcupitt\Vips\FFI::newGClosure(); + \Jcupitt\Vips\FFI::gobject()->g_closure_set_marshal($gc, $marshaler); + \Jcupitt\Vips\FFI::gobject()->g_signal_connect_closure($this->pointer, $name, $gc, 0); + } + private static function getMarshaler(string $name, callable $callback): ?Closure + { + switch ($name) { + case 'preeval': + case 'eval': + case 'posteval': + return static function (CData $gClosure, ?CData $returnValue, int $numberOfParams, CData $params, CData $hint, ?CData $data) use (&$callback) { + assert($numberOfParams === 2); + /** + * Signature: void(VipsImage* image, void* progress, void* handle) + */ + $vi = \Jcupitt\Vips\FFI::gobject()->g_value_get_object(\FFI::addr($params[0])); + \Jcupitt\Vips\FFI::gobject()->g_object_ref($vi); + $image = new \Jcupitt\Vips\Image($vi); + $pr = \Jcupitt\Vips\FFI::vips()->cast(\Jcupitt\Vips\FFI::ctypes('VipsProgress'), \Jcupitt\Vips\FFI::gobject()->g_value_get_pointer(\FFI::addr($params[1]))); + $callback($image, $pr); + }; + case 'read': + if (\Jcupitt\Vips\FFI::atLeast(8, 9)) { + return static function (CData $gClosure, CData $returnValue, int $numberOfParams, CData $params, CData $hint, ?CData $data) use (&$callback): void { + assert($numberOfParams === 3); + /** + * Signature: gint64(VipsSourceCustom* source, void* buffer, gint64 length, void* handle) + */ + $bufferLength = (int) \Jcupitt\Vips\FFI::gobject()->g_value_get_int64(\FFI::addr($params[2])); + $returnBuffer = $callback($bufferLength); + $returnBufferLength = 0; + if ($returnBuffer !== null) { + $returnBufferLength = strlen($returnBuffer); + $bufferPointer = \Jcupitt\Vips\FFI::gobject()->g_value_get_pointer(\FFI::addr($params[1])); + \FFI::memcpy($bufferPointer, $returnBuffer, $returnBufferLength); + } + \Jcupitt\Vips\FFI::gobject()->g_value_set_int64($returnValue, $returnBufferLength); + }; + } + return null; + case 'seek': + if (\Jcupitt\Vips\FFI::atLeast(8, 9)) { + return static function (CData $gClosure, CData $returnValue, int $numberOfParams, CData $params, CData $hint, ?CData $data) use (&$callback): void { + assert($numberOfParams === 3); + /** + * Signature: gint64(VipsSourceCustom* source, gint64 offset, int whence, void* handle) + */ + $offset = (int) \Jcupitt\Vips\FFI::gobject()->g_value_get_int64(\FFI::addr($params[1])); + $whence = (int) \Jcupitt\Vips\FFI::gobject()->g_value_get_int(\FFI::addr($params[2])); + \Jcupitt\Vips\FFI::gobject()->g_value_set_int64($returnValue, $callback($offset, $whence)); + }; + } + return null; + case 'write': + if (\Jcupitt\Vips\FFI::atLeast(8, 9)) { + return static function (CData $gClosure, CData $returnValue, int $numberOfParams, CData $params, CData $hint, ?CData $data) use (&$callback): void { + assert($numberOfParams === 3); + /** + * Signature: gint64(VipsTargetCustom* target, void* buffer, gint64 length, void* handle) + */ + $bufferPointer = \Jcupitt\Vips\FFI::gobject()->g_value_get_pointer(\FFI::addr($params[1])); + $bufferLength = (int) \Jcupitt\Vips\FFI::gobject()->g_value_get_int64(\FFI::addr($params[2])); + $buffer = \FFI::string($bufferPointer, $bufferLength); + $returnBufferLength = $callback($buffer); + \Jcupitt\Vips\FFI::gobject()->g_value_set_int64($returnValue, $returnBufferLength); + }; + } + return null; + case 'finish': + if (\Jcupitt\Vips\FFI::atLeast(8, 9)) { + return static function (CData $gClosure, ?CData $returnValue, int $numberOfParams, CData $params, CData $hint, ?CData $data) use (&$callback): void { + assert($numberOfParams === 1); + /** + * Signature: void(VipsTargetCustom* target, void* handle) + */ + $callback(); + }; + } + return null; + case 'end': + if (\Jcupitt\Vips\FFI::atLeast(8, 13)) { + return static function (CData $gClosure, CData $returnValue, int $numberOfParams, CData $params, CData $hint, ?CData $data) use (&$callback): void { + assert($numberOfParams === 1); + /** + * Signature: int(VipsTargetCustom* target, void* handle) + */ + \Jcupitt\Vips\FFI::gobject()->g_value_set_int($returnValue, $callback()); + }; + } + return null; + default: + return null; + } + } +} +/* + * Local variables: + * tab-width: 4 + * c-basic-offset: 4 + * End: + * vim600: expandtab sw=4 ts=4 fdm=marker + * vim<600: expandtab sw=4 ts=4 + */ diff --git a/src/wp-includes/php-vips/src/GValue.php b/src/wp-includes/php-vips/src/GValue.php new file mode 100644 index 0000000000000..43f6949ae3692 --- /dev/null +++ b/src/wp-includes/php-vips/src/GValue.php @@ -0,0 +1,287 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/libvips/php-vips + */ +namespace Jcupitt\Vips; + +class GValue +{ + private \FFI\CData $struct; + public \FFI\CData $pointer; + public function __construct() + { + # allocate a gvalue on the heap, and make it persistent between requests + $this->struct = \Jcupitt\Vips\FFI::gobject()->new("GValue", \true, \true); + $this->pointer = \FFI::addr($this->struct); + # GValue needs to be inited to all zero + \FFI::memset($this->pointer, 0, \FFI::sizeof($this->struct)); + } + /** + * Turn a string into an enum value, if possible + * @throws Exception + */ + public static function toEnum(int $gtype, $value): int + { + if (is_string($value)) { + $enum_value = \Jcupitt\Vips\FFI::vips()->vips_enum_from_nick("php-vips", $gtype, $value); + if ($enum_value < 0) { + throw new \Jcupitt\Vips\Exception(); + } + } else { + $enum_value = $value; + } + return $enum_value; + } + /** + * Turn an enum into a string, if possible + * @throws Exception + */ + public static function fromEnum(int $gtype, int $value): string + { + $result = \Jcupitt\Vips\FFI::vips()->vips_enum_nick($gtype, $value); + if ($result === null) { + throw new \Jcupitt\Vips\Exception("value not in enum"); + } + return $result; + } + public function __destruct() + { + \Jcupitt\Vips\FFI::gobject()->g_value_unset($this->pointer); + } + public function setType(int $gtype): void + { + \Jcupitt\Vips\FFI::gobject()->g_value_init($this->pointer, $gtype); + } + public function getType(): int + { + return $this->pointer->g_type; + } + /** + * Set a GValue. + * + * @param mixed $value Value to be set. + * + * @throws Exception + */ + public function set($value): void + { + $gtype = $this->getType(); + switch ($gtype) { + case \Jcupitt\Vips\FFI::gtypes("gboolean"): + \Jcupitt\Vips\FFI::gobject()->g_value_set_boolean($this->pointer, $value); + break; + case \Jcupitt\Vips\FFI::gtypes("gint"): + \Jcupitt\Vips\FFI::gobject()->g_value_set_int($this->pointer, $value); + break; + case \Jcupitt\Vips\FFI::gtypes("gint64"): + \Jcupitt\Vips\FFI::gobject()->g_value_set_int64($this->pointer, $value); + break; + case \Jcupitt\Vips\FFI::gtypes("guint64"): + \Jcupitt\Vips\FFI::gobject()->g_value_set_uint64($this->pointer, $value); + break; + case \Jcupitt\Vips\FFI::gtypes("gdouble"): + \Jcupitt\Vips\FFI::gobject()->g_value_set_double($this->pointer, $value); + break; + case \Jcupitt\Vips\FFI::gtypes("gchararray"): + \Jcupitt\Vips\FFI::gobject()->g_value_set_string($this->pointer, $value); + break; + case \Jcupitt\Vips\FFI::gtypes("VipsRefString"): + \Jcupitt\Vips\FFI::vips()->vips_value_set_ref_string($this->pointer, $value); + break; + case \Jcupitt\Vips\FFI::gtypes("VipsArrayInt"): + if (!is_array($value)) { + $value = [$value]; + } + $n = count($value); + $array = \Jcupitt\Vips\FFI::vips()->new("int[{$n}]"); + for ($i = 0; $i < $n; $i++) { + $array[$i] = $value[$i]; + } + \Jcupitt\Vips\FFI::vips()->vips_value_set_array_int($this->pointer, $array, $n); + break; + case \Jcupitt\Vips\FFI::gtypes("VipsArrayDouble"): + if (!is_array($value)) { + $value = [$value]; + } + $n = count($value); + $array = \Jcupitt\Vips\FFI::vips()->new("double[{$n}]"); + for ($i = 0; $i < $n; $i++) { + $array[$i] = $value[$i]; + } + \Jcupitt\Vips\FFI::vips()->vips_value_set_array_double($this->pointer, $array, $n); + break; + case \Jcupitt\Vips\FFI::gtypes("VipsArrayImage"): + if (!is_array($value)) { + $value = [$value]; + } + $n = count($value); + \Jcupitt\Vips\FFI::vips()->vips_value_set_array_image($this->pointer, $n); + $array = \Jcupitt\Vips\FFI::vips()->vips_value_get_array_image($this->pointer, null); + for ($i = 0; $i < $n; $i++) { + $image = $value[$i]; + $array[$i] = $image->pointer; + $image->ref(); + } + break; + case \Jcupitt\Vips\FFI::gtypes("VipsBlob"): + # we need to set the blob to a copy of the data that vips_lib + # can own and free + $n = strlen($value); + $memory = \Jcupitt\Vips\FFI::vips()->new("char[{$n}]", \false, \true); + \FFI::memcpy($memory, $value, $n); + \Jcupitt\Vips\FFI::vips()->vips_value_set_blob_free($this->pointer, $memory, $n); + break; + default: + $fundamental = \Jcupitt\Vips\FFI::gobject()->g_type_fundamental($gtype); + switch ($fundamental) { + case \Jcupitt\Vips\FFI::gtypes("GObject"): + \Jcupitt\Vips\FFI::gobject()->g_value_set_object($this->pointer, $value->pointer); + break; + case \Jcupitt\Vips\FFI::gtypes("GEnum"): + \Jcupitt\Vips\FFI::gobject()->g_value_set_enum($this->pointer, self::toEnum($gtype, $value)); + break; + case \Jcupitt\Vips\FFI::gtypes("GFlags"): + /* Just set as int. + */ + \Jcupitt\Vips\FFI::gobject()->g_value_set_flags($this->pointer, $value); + break; + default: + $typeName = \Jcupitt\Vips\FFI::gobject()->g_type_name($gtype); + throw new \BadMethodCallException("gtype {$typeName} ({$gtype}) not implemented"); + } + } + } + /** + * Get the contents of a GValue. + * + * @return mixed The contents of this GValue. + * + * @throws Exception + */ + public function get() + { + $gtype = $this->getType(); + $result = null; + switch ($gtype) { + case \Jcupitt\Vips\FFI::gtypes("gboolean"): + $result = \Jcupitt\Vips\FFI::gobject()->g_value_get_boolean($this->pointer); + break; + case \Jcupitt\Vips\FFI::gtypes("gint"): + $result = \Jcupitt\Vips\FFI::gobject()->g_value_get_int($this->pointer); + break; + case \Jcupitt\Vips\FFI::gtypes("gint64"): + $result = \Jcupitt\Vips\FFI::gobject()->g_value_get_int64($this->pointer); + break; + case \Jcupitt\Vips\FFI::gtypes("guint64"): + $result = \Jcupitt\Vips\FFI::gobject()->g_value_get_uint64($this->pointer); + break; + case \Jcupitt\Vips\FFI::gtypes("gdouble"): + $result = \Jcupitt\Vips\FFI::gobject()->g_value_get_double($this->pointer); + break; + case \Jcupitt\Vips\FFI::gtypes("gchararray"): + $result = \Jcupitt\Vips\FFI::gobject()->g_value_get_string($this->pointer); + break; + case \Jcupitt\Vips\FFI::gtypes("VipsRefString"): + $p_size = \Jcupitt\Vips\FFI::vips()->new("size_t[1]"); + $result = \Jcupitt\Vips\FFI::vips()->vips_value_get_ref_string($this->pointer, $p_size); + # $p_size[0] will be the string length, but assume it's null + # terminated + break; + case \Jcupitt\Vips\FFI::gtypes("VipsImage"): + $pointer = \Jcupitt\Vips\FFI::gobject()->g_value_get_object($this->pointer); + $result = new \Jcupitt\Vips\Image($pointer); + // get_object does not increment the ref count + $result->ref(); + break; + case \Jcupitt\Vips\FFI::gtypes("VipsArrayInt"): + $p_len = \Jcupitt\Vips\FFI::vips()->new("int[1]"); + $pointer = \Jcupitt\Vips\FFI::vips()->vips_value_get_array_int($this->pointer, $p_len); + $result = []; + for ($i = 0; $i < $p_len[0]; $i++) { + $result[] = $pointer[$i]; + } + break; + case \Jcupitt\Vips\FFI::gtypes("VipsArrayDouble"): + $p_len = \Jcupitt\Vips\FFI::vips()->new("int[1]"); + $pointer = \Jcupitt\Vips\FFI::vips()->vips_value_get_array_double($this->pointer, $p_len); + $result = []; + for ($i = 0; $i < $p_len[0]; $i++) { + $result[] = $pointer[$i]; + } + break; + case \Jcupitt\Vips\FFI::gtypes("VipsArrayImage"): + $p_len = \Jcupitt\Vips\FFI::vips()->new("int[1]"); + $pointer = \Jcupitt\Vips\FFI::vips()->vips_value_get_array_image($this->pointer, $p_len); + $result = []; + for ($i = 0; $i < $p_len[0]; $i++) { + $image = new \Jcupitt\Vips\Image($pointer[$i]); + $image->ref(); + $result[] = $image; + } + break; + case \Jcupitt\Vips\FFI::gtypes("VipsBlob"): + $p_len = \Jcupitt\Vips\FFI::vips()->new("size_t[1]"); + $pointer = \Jcupitt\Vips\FFI::vips()->vips_value_get_blob($this->pointer, $p_len); + $result = \FFI::string($pointer, $p_len[0]); + break; + default: + $fundamental = \Jcupitt\Vips\FFI::gobject()->g_type_fundamental($gtype); + switch ($fundamental) { + case \Jcupitt\Vips\FFI::gtypes("GEnum"): + $result = \Jcupitt\Vips\FFI::gobject()->g_value_get_enum($this->pointer); + $result = self::fromEnum($gtype, $result); + break; + case \Jcupitt\Vips\FFI::gtypes("GFlags"): + /* Just get as int. + */ + $result = \Jcupitt\Vips\FFI::gobject()->g_value_get_flags($this->pointer); + break; + default: + $typeName = \Jcupitt\Vips\FFI::gobject()->g_type_name($gtype); + throw new \BadMethodCallException("gtype {$typeName} ({$gtype}) not implemented"); + } + } + return $result; + } +} +/* +* Local variables: +* tab-width: 4 +* c-basic-offset: 4 +* End: +* vim600: expandtab sw=4 ts=4 fdm=marker +* vim<600: expandtab sw=4 ts=4 +*/ diff --git a/src/wp-includes/php-vips/src/Image.php b/src/wp-includes/php-vips/src/Image.php new file mode 100644 index 0000000000000..3891071dc1542 --- /dev/null +++ b/src/wp-includes/php-vips/src/Image.php @@ -0,0 +1,2224 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * This class represents a Vips image object. + * + * This module provides a binding for the [vips image processing + * library](https://libvips.org) version 8.7 and later, and requires PHP 7.4 + * and later. + * + * # Example + * + * ```php + * 'sequential']); + * $im = $im->crop(100, 100, $im->width - 200, $im->height - 200); + * $im = $im->reduce(1.0 / 0.9, 1.0 / 0.9, ['kernel' => 'linear']); + * $mask = Vips\Image::newFromArray( + * [[-1, -1, -1], + * [-1, 16, -1], + * [-1, -1, -1]], 8); + * $im = $im->conv($mask); + * $im->writeToFile($argv[2]); + * ?> + * ``` + * + * You'll need this in your `composer.json`: + * + * ``` + * "require": { + * "jcupitt/vips" : "2.0.0" + * } + * ``` + * + * And run with: + * + * ``` + * $ composer install + * $ ./try1.php ~/pics/k2.jpg x.tif + * ``` + * + * This example loads a file, crops 100 pixels from every edge, reduces by 10% + * using a bilinear interpolator (the default is lanczos3), + * sharpens the image, and saves it back to disc again. + * + * Reading this example line by line, we have: + * + * ```php + * $im = Vips\Image::newFromFile($argv[1], ['access' => 'sequential']); + * ``` + * + * `Image::newFromFile` can load any image file supported by vips. Almost all + * operations can be given an array of options as a final argument. + * + * In this + * example, we will be accessing pixels top-to-bottom as we sweep through the + * image reading and writing, so `sequential` access mode is best for us. The + * default mode is `random`, this allows for full random access to image pixels, + * but is slower and needs more memory. + * + * You can also load formatted images from strings or create images from + * PHP arrays. + * + * See the [main libvips + * documentation](https://www.libvips.org/API/current/VipsImage.html#vips-image-new-from-file) + * for a more detailed explaination. + * + * The next line: + * + * ```php + * $im = $im->crop(100, 100, $im->width - 200, $im->height - 200); + * ``` + * + * Crops 100 pixels from every edge. You can access any vips image property + * directly as a PHP property. If the vips property name does not + * conform to PHP naming conventions, you can use something like + * `$image->get('ipct-data')`. + * + * Use `$image->getFields()` to get an array of all the possible field names. + * + * Next we have: + * + * ```php + * $mask = Vips\Image::newFromArray( + * [[-1, -1, -1], + * [-1, 16, -1], + * [-1, -1, -1]], 8); + * $im = $im->conv($mask); + * ``` + * + * `Image::newFromArray` creates an image from an array constant. The 8 at + * the end sets the scale: the amount to divide the image by after + * integer convolution. See the libvips API docs for `vips_conv()` (the operation + * invoked by `Image::conv`) for details on the convolution operator. See + * **Getting more help** below. + * + * Finally: + * + * ```php + * $im->writeToFile($argv[2]); + * ``` + * + * `Image::writeToFile` writes an image back to the filesystem. It can + * write any format supported by vips: the file type is set from the filename + * suffix. You can write formatted images to strings, and pixel values to + * arrays. + * + * # Getting more help + * + * This binding lets you call the complete C API almost directly. You should + * [consult the C docs](https://jcupitt.github.io/libvips/API/current) + * for full details on the operations that are available and + * the arguments they take. There's a handy [function + * list](https://jcupitt.github.io/libvips/API/current/func-list.html) + * which summarises the operations in the library. You can use the `vips` + * command-line interface to get help as well, for example: + * + * ``` + * $ vips embed + * embed an image in a larger image + * usage: + * embed in out x y width height + * where: + * in - Input image, input VipsImage + * out - Output image, output VipsImage + * x - Left edge of input in output, input gint + * default: 0 + * min: -1000000000, max: 1000000000 + * y - Top edge of input in output, input gint + * default: 0 + * min: -1000000000, max: 1000000000 + * width - Image width in pixels, input gint + * default: 1 + * min: 1, max: 1000000000 + * height - Image height in pixels, input gint + * default: 1 + * min: 1, max: 1000000000 + * optional arguments: + * extend - How to generate the extra pixels, input VipsExtend + * default: black + * allowed: black, copy, repeat, mirror, white, background + * background - Colour for background pixels, input VipsArrayDouble + * operation flags: sequential-unbuffered + * ``` + * + * You can call this from PHP as: + * + * ```php + * $out = $in->embed($x, $y, $width, $height, + * ['extend' => 'copy', 'background' => [1, 2, 3]]); + * ``` + * + * `'background'` can also be a simple constant, such as `12`, see below. + * + * The `vipsheader` command-line program is an easy way to see all the + * properties of an image. For example: + * + * ``` + * $ vipsheader -a ~/pics/k2.jpg + * /home/john/pics/k2.jpg: 1450x2048 uchar, 3 bands, srgb, jpegload + * width: 1450 + * height: 2048 + * bands: 3 + * format: 0 - uchar + * coding: 0 - none + * interpretation: 22 - srgb + * xoffset: 0 + * yoffset: 0 + * xres: 2.834646 + * yres: 2.834646 + * filename: "/home/john/pics/k2.jpg" + * vips-loader: jpegload + * jpeg-multiscan: 0 + * ipct-data: VIPS_TYPE_BLOB, data = 0x20f0010, length = 332 + * ``` + * + * You can access any of these fields as PHP properties of the `Image` class. + * Use `$image->get('ipct-data')` for property names which are not valid under + * PHP syntax. + * + * # Automatic wrapping + * + * This binding has a `__call()` method and uses + * it to look up vips operations. For example, the libvips operation `embed`, + * which appears in C as `vips_embed()`, appears in PHP as `Image::embed`. + * + * The operation's list of required arguments is searched and the first input + * image is set to the value of `self`. Operations which do not take an input + * image, such as `Image::black`, appear as static methods. The remainder of + * the arguments you supply in the function call are used to set the other + * required input arguments. If the final supplied argument is an array, it is + * used to set any optional input arguments. The result is the required output + * argument if there is only one result, or an array of values if the operation + * produces several results. + * + * For example, `Image::min`, the vips operation that searches an image for + * the minimum value, has a large number of optional arguments. You can use it + * to find the minimum value like this: + * + * ```php + * $min_value = $image->min(); + * ``` + * + * You can ask it to return the position of the minimum with `x` and `y`. + * + * ```php + * $result = $image->min(['x' => true, 'y' => true]); + * $min_value = $result['out']; + * $x_pos = $result['x']; + * $y_pos = $result['y']; + * ``` + * + * Now `x_pos` and `y_pos` will have the coordinates of the minimum value. + * There's actually a convenience function for this, `Image::minpos`, see + * below. + * + * You can also ask for the top *n* minimum, for example: + * + * ```php + * $result = $image->min(['size' => 10, 'x_array' => true, 'y_array' => true]); + * $x_pos = $result['x_array']; + * $y_pos = $result['y_array']; + * ``` + * + * Now `x_pos` and `y_pos` will be 10-element arrays. + * + * Because operations are member functions and return the result image, you can + * chain them. For example, you can write: + * + * ```php + * $result_image = $image->real()->cos(); + * ``` + * + * to calculate the cosine of the real part of a complex image. + * + * libvips types are also automatically wrapped and unwrapped. The binding + * looks at the type + * of argument required by the operation and converts the value you supply, + * when it can. For example, `Image::linear` takes a `VipsArrayDouble` as + * an argument + * for the set of constants to use for multiplication. You can supply this + * value as an integer, a float, or some kind of compound object and it + * will be converted for you. You can write: + * + * ```php + * $result = $image->linear(1, 3); + * $result = $image->linear(12.4, 13.9); + * $result = $image->linear([1, 2, 3], [4, 5, 6]); + * $result = $image->linear(1, [4, 5, 6]); + * ``` + * + * And so on. You can also use `Image::add()` and friends, see below. + * + * It does a couple of more ambitious conversions. It will automatically convert + * to and from the various vips types, like `VipsBlob` and `VipsArrayImage`. For + * example, you can read the ICC profile out of an image like this: + * + * ```php + * $profile = $image->get('icc-profile-data'); + * ``` + * + * and `$profile` will be a PHP string. + * + * If an operation takes several input images, you can use a constant for all but + * one of them and the wrapper will expand the constant to an image for you. For + * example, `Image::ifthenelse()` uses a condition image to pick pixels + * between a then and an else image: + * + * ```php + * $result = $condition->ifthenelse($then_image, $else_image); + * ``` + * + * You can use a constant instead of either the then or the else parts and it + * will be expanded to an image for you. If you use a constant for both then and + * else, it will be expanded to match the condition image. For example: + * + * ```php + * $result = $condition->ifthenelse([0, 255, 0], [255, 0, 0]); + * ``` + * + * Will make an image where true pixels are green and false pixels are red. + * + * This is useful for `Image::bandjoin`, the thing to join two or more + * images up bandwise. You can write: + * + * ```php + * $rgba = $rgb->bandjoin(255); + * ``` + * + * to append a constant 255 band to an image, perhaps to add an alpha channel. Of + * course you can also write: + * + * ```php + * $result = $image->bandjoin($image2); + * $result = $image->bandjoin([image2, image3]); + * $result = Image::bandjoin([image1, image2, image3]); + * $result = $image->bandjoin([image2, 255]); + * ``` + * + * and so on. + * + * # Array access + * + * Images can be treated as arrays of bands. You can write: + * + * ```php + * $result = $image[1]; + * ``` + * + * to get band 1 from an image (green, in an RGB image). + * + * You can assign to bands as well. You can write: + * + * ```php + * $image[1] = $other_image; + * ``` + * + * And band 1 will be replaced by all the bands in `$other_image` using + * `bandjoin`. Use no offset to mean append, use -1 to mean prepend: + * + * ```php + * $image[] = $other_image; // append bands from other + * $image[-1] = $other_image; // prepend bands from other + * ``` + * + * You can use number and array constants as well, for example: + * + * ```php + * $image[] = 255; // append a constant 255 + * $image[1] = [1, 2, 3]; // swap band 1 for three constant bands + * ``` + * + * Finally, you can delete bands with `unset`: + * + * ```php + * unset($image[1]); // remove band 1 + * ``` + * + * # Exceptions + * + * The wrapper spots errors from vips operations and throws + * `Vips\Exception`. You can catch it in the usual way. + * + * # Draw operations + * + * Paint operations like `Image::draw_circle` and `Image::draw_line` + * modify their input image. This + * makes them hard to use with the rest of libvips: you need to be very careful + * about the order in which operations execute or you can get nasty crashes. + * + * The wrapper spots operations of this type and makes a private copy of the + * image in memory before calling the operation. This stops crashes, but it does + * make it inefficient. If you draw 100 lines on an image, for example, you'll + * copy the image 100 times. The wrapper does make sure that memory is recycled + * where possible, so you won't have 100 copies in memory. + * + * If you want to avoid the copies, you'll need to call drawing operations + * yourself. + * + * # Thumbnailing + * + * The thumbnailing functionality is implemented by `Vips\Image::thumbnail` and + * `Vips\Image::thumbnail_buffer` (which thumbnails an image held as a string). + * + * You could write: + * + * ```php + * $filename = 'image.jpg'; + * $image = Vips\Image::thumbnail($filename, 200, ['height' => 200]); + * $image->writeToFile('my-thumbnail.jpg'); + * ``` + * + * # Resample + * + * There are three types of operation in this section. + * + * First, `->affine()` applies an affine transform to an image. + * This is any sort of 2D transform which preserves straight lines; + * so any combination of stretch, sheer, rotate and translate. + * You supply an interpolator for it to use to generate pixels + * (@see Image::newInterpolator()). It will not produce good results for + * very large shrinks: you'll see aliasing. + * + * `->reduce()` is like `->affine()`, but it can only shrink images, + * it can't enlarge, rotate, or skew. + * It's very fast and uses an adaptive kernel (@see Kernel for possible values) + * for interpolation. It will be slow for very large shrink factors. + * + * `->shrink()` is a fast block shrinker. It can quickly reduce images by large + * integer factors. It will give poor results for small size reductions: + * again, you'll see aliasing. + * + * Next, `->resize()` specialises in the common task of image reduce and enlarge. + * It strings together combinations of `->shrink()`, `->reduce()`, `->affine()` + * and others to implement a general, high-quality image resizer. + * + * Finally, `->mapim()` can apply arbitrary 2D image transforms to an image. + * + * # Expansions + * + * Some vips operators take an enum to select an action, for example + * `Image::math` can be used to calculate sine of every pixel like this: + * + * ```php + * $result = $image->math('sin'); + * ``` + * + * This is annoying, so the wrapper expands all these enums into separate members + * named after the enum. So you can write: + * + * ```php + * $result = $image->sin(); + * ``` + * + * # Convenience functions + * + * The wrapper defines a few extra useful utility functions: + * `Image::get`, `Image::set`, `Image::bandsplit`, + * `Image::maxpos`, `Image::minpos`, + * `Image::median`. See below. + * + * # Logging + * + * Use `Config::setLogger` to enable logging in the usual manner. A + * sample logger, handy for debugging, is defined in `Vips\DebugLogger`. You + * can enable debug logging with: + * + * ```php + * Vips\Config::setLogger(new Vips\DebugLogger); + * ``` + * + * # Configuration + * + * You can use the methods in `Vips\Config` to set various global properties of + * the library. For example, you can control the size of the libvips cache, + * or the size of the worker threadpools that libvips uses to evaluate images. + * + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +class Image extends \Jcupitt\Vips\ImageAutodoc implements \ArrayAccess +{ + /** + * A pointer to the underlying VipsImage. This is the same as the + * GObject, just cast to VipsImage to help FFI. + * + * @internal + */ + public \FFI\CData $pointer; + /** + * Wrap an Image around an underlying CData pointer. + * + * Don't call this yourself, users should stick to (for example) + * Image::newFromFile(). + * + * @internal + */ + public function __construct(\FFI\CData $pointer) + { + $this->pointer = \Jcupitt\Vips\FFI::vips()->cast(\Jcupitt\Vips\FFI::ctypes("VipsImage"), $pointer); + parent::__construct($pointer); + } + /** + * Apply a func to every numeric member of $value. Useful for self::subtract + * etc. + * + * @param mixed $value The thing we walk. + * @param \Closure $func Apply this. + * + * @return mixed The updated $value. + * + * @internal + */ + private static function mapNumeric($value, \Closure $func) + { + if (is_numeric($value)) { + $value = $func($value); + } elseif (is_array($value)) { + array_walk_recursive($value, function (&$value) use ($func) { + $value = self::mapNumeric($value, $func); + }); + } + return $value; + } + /** + * Is a $value a rectangular 2D array? + * + * @param mixed $value Test this. + * + * @return bool true if this is a 2D array. + * + * @internal + */ + private static function is2D($value): bool + { + if (!is_array($value)) { + return \false; + } + if (!is_array($value[0])) { + return \false; + } + $width = count($value[0]); + foreach ($value as $row) { + if (!is_array($row) || count($row) !== $width) { + return \false; + } + } + return \true; + } + /** + * Is $value something that we should treat as an image? + * + * Instance of Image, or 2D arrays are images; 1D arrays or single values + * are constants. + * + * @param mixed $value The value to test. + * + * @return bool true if this is like an image. + * + * @internal + */ + public static function isImageish($value): bool + { + return self::is2D($value) || $value instanceof \Jcupitt\Vips\Image; + } + /** + * Turn a constant (eg. 1, '12', [1, 2, 3], [[1]]) into an image using + * this as a guide. + * + * @param mixed $value Turn this into an image. + * + * @throws Exception + * + * @return Image The image we created. + * + * @internal + */ + public function imageize($value): \Jcupitt\Vips\Image + { + if ($value instanceof \Jcupitt\Vips\Image) { + return $value; + } elseif (self::is2D($value)) { + return self::newFromArray($value); + } else { + return $this->newFromImage($value); + } + } + /** + * Run a function expecting a complex image. If the image is not in complex + * format, try to make it complex by joining adjacant bands as real and + * imaginary. + * + * @param \Closure $func The function to run. + * @param Image $image The image to run the function on. + * + * @throws Exception + * + * @return Image A new Image. + * + * @internal + */ + private static function runCmplx(\Closure $func, \Jcupitt\Vips\Image $image): \Jcupitt\Vips\Image + { + $original_format = $image->format; + if ($image->format != 'complex' && $image->format != 'dpcomplex') { + if ($image->bands % 2 != 0) { + throw new \Jcupitt\Vips\Exception('not an even number of bands'); + } + if ($image->format != 'float' && $image->format != 'double') { + $image = $image->cast('float'); + } + if ($image->format == 'double') { + $new_format = 'dpcomplex'; + } else { + $new_format = 'complex'; + } + $image = $image->copy(['format' => $new_format, 'bands' => $image->bands / 2]); + } + $image = $func($image); + if ($original_format != 'complex' && $original_format != 'dpcomplex') { + if ($image->format == 'dpcomplex') { + $new_format = 'double'; + } else { + $new_format = 'float'; + } + $image = $image->copy(['format' => $new_format, 'bands' => $image->bands * 2]); + } + return $image; + } + /** + * Handy for things like self::more. Call a 2-ary vips operator like + * 'more', but if the arg is not an image (i.e. it's a constant), call + * 'more_const' instead. + * + * @param mixed $other The right-hand argument. + * @param string $base The base part of the operation name. + * @param string $op The action to invoke. + * @param array $options An array of options to pass to the operation. + * + * @throws Exception + * + * @return mixed The operation result. + * + * @internal + */ + private function callEnum($other, string $base, string $op, array $options = []) + { + if (self::isImageish($other)) { + return \Jcupitt\Vips\VipsOperation::call($base, $this, [$other, $op], $options); + } else { + return \Jcupitt\Vips\VipsOperation::call($base . '_const', $this, [$op, $other], $options); + } + } + /** + * Find the name of the load operation vips will use to load a file, for + * example "VipsForeignLoadJpegFile". You can use this to work out what + * options to pass to newFromFile(). + * + * @param string $filename The file to test. + * + * @return string|null The name of the load operation, or null. + */ + public static function findLoad(string $filename): ?string + { + return \Jcupitt\Vips\FFI::vips()->vips_foreign_find_load($filename); + } + /** + * Create a new Image from a file on disc. + * + * See the [main libvips + * documentation](https://www.libvips.org/API/current/VipsImage.html#vips-image-new-from-file) + * for a more detailed explaination. + * + * @param string $name The file to open. + * @param array $options Any options to pass on to the load operation. + * + * @throws Exception + * + * @return Image A new Image. + */ + public static function newFromFile(string $name, array $options = []): \Jcupitt\Vips\Image + { + $filename = \Jcupitt\Vips\Utils::filenameGetFilename($name); + $string_options = \Jcupitt\Vips\Utils::filenameGetOptions($name); + $loader = self::findLoad($filename); + if ($loader == null) { + throw new \Jcupitt\Vips\Exception(); + } + if (strlen($string_options) != 0) { + $options = array_merge(["string_options" => $string_options], $options); + } + return \Jcupitt\Vips\VipsOperation::call($loader, null, [$filename], $options); + } + /** + * Find the name of the load operation vips will use to load a buffer, for + * example 'VipsForeignLoadJpegBuffer'. You can use this to work out what + * options to pass to newFromBuffer(). + * + * @param string $buffer The formatted image to test. + * + * @return string|null The name of the load operation, or null. + */ + public static function findLoadBuffer(string $buffer): ?string + { + return \Jcupitt\Vips\FFI::vips()->vips_foreign_find_load_buffer($buffer, strlen($buffer)); + } + /** + * Create a new Image from a compressed image held as a string. + * + * @param string $buffer The formatted image to open. + * @param string $string_options Any text-style options to pass to the + * selected loader. + * @param array $options Options to pass on to the load operation. + * + * @throws Exception + * + * @return Image A new Image. + */ + public static function newFromBuffer(string $buffer, string $string_options = '', array $options = []): \Jcupitt\Vips\Image + { + $loader = self::findLoadBuffer($buffer); + if ($loader == null) { + throw new \Jcupitt\Vips\Exception(); + } + if (strlen($string_options) != 0) { + $options = array_merge(["string_options" => $string_options], $options); + } + return \Jcupitt\Vips\VipsOperation::call($loader, null, [$buffer], $options); + } + /** + * Create a new Image from a php array. + * + * 2D arrays become 2D images. 1D arrays become 2D images with height 1. + * + * @param array $array The array to make the image from. + * @param float $scale The "scale" metadata item. Useful for integer + * convolution masks. + * @param float $offset The "offset" metadata item. Useful for integer + * convolution masks. + * + * @throws Exception + * + * @return Image A new Image. + */ + public static function newFromArray(array $array, float $scale = 1.0, float $offset = 0.0): \Jcupitt\Vips\Image + { + if (!self::is2D($array)) { + $array = [$array]; + } + $height = count($array); + $width = count($array[0]); + $n = $width * $height; + $a = \Jcupitt\Vips\FFI::vips()->new("double[{$n}]", \true, \true); + for ($y = 0; $y < $height; $y++) { + for ($x = 0; $x < $width; $x++) { + $a[$x + $y * $width] = $array[$y][$x]; + } + } + $pointer = \Jcupitt\Vips\FFI::vips()->vips_image_new_matrix_from_array($width, $height, $a, $n); + if ($pointer == null) { + throw new \Jcupitt\Vips\Exception(); + } + $result = new \Jcupitt\Vips\Image($pointer); + $result->setType(\Jcupitt\Vips\FFI::gtypes("gdouble"), 'scale', $scale); + $result->setType(\Jcupitt\Vips\FFI::gtypes("gdouble"), 'offset', $offset); + return $result; + } + /** + * Wraps an Image around an area of memory containing a C-style array. + * + * @param mixed $data C-style array. + * @param int $width Image width in pixels. + * @param int $height Image height in pixels. + * @param int $bands Number of bands. + * @param string $format Band format. (@see BandFormat) + * + * @throws Exception + * + * @return Image A new Image. + */ + public static function newFromMemory($data, int $width, int $height, int $bands, string $format): \Jcupitt\Vips\Image + { + /* Take a copy of the memory area to avoid lifetime issues. + * + * TODO add a references system instead, see pyvips. + */ + $pointer = \Jcupitt\Vips\FFI::vips()->vips_image_new_from_memory_copy($data, strlen($data), $width, $height, $bands, $format); + if ($pointer == null) { + throw new \Jcupitt\Vips\Exception(); + } + return new \Jcupitt\Vips\Image($pointer); + } + /** + * Deprecated thing to make an interpolator. + * + * See Interpolator::newFromName() for the new thing. + */ + public static function newInterpolator(string $name): \Jcupitt\Vips\Interpolate + { + return \Jcupitt\Vips\Interpolate::newFromName($name); + } + /** + * Create a new image from a constant. + * + * The new image has the same width, height, format, interpretation, xres, + * yres, xoffset, yoffset as $this, but each pixel has the constant value + * $value. + * + * Pass a single number to make a one-band image, pass an array of numbers + * to make an N-band image. + * + * @param mixed $value The value to set each pixel to. + * + * @throws Exception + * + * @return Image A new Image. + */ + public function newFromImage($value): \Jcupitt\Vips\Image + { + $pixel = static::black(1, 1)->add($value)->cast($this->format); + $image = $pixel->embed(0, 0, $this->width, $this->height, ['extend' => \Jcupitt\Vips\Extend::COPY]); + return $image->copy(['interpretation' => $this->interpretation, 'xres' => $this->xres, 'yres' => $this->yres, 'xoffset' => $this->xoffset, 'yoffset' => $this->yoffset]); + } + /** + * Find the name of the load operation vips will use to load a VipsSource, for + * example 'VipsForeignLoadJpegSource'. You can use this to work out what + * options to pass to newFromSource(). + * + * @param Source $source The source to test + * @return string|null The name of the load operation, or null. + */ + public static function findLoadSource(\Jcupitt\Vips\Source $source): ?string + { + return \Jcupitt\Vips\FFI::vips()->vips_foreign_find_load_source(\Jcupitt\Vips\FFI::vips()->cast(\Jcupitt\Vips\FFI::ctypes('VipsSource'), $source->pointer)); + } + /** + * @throws Exception + */ + public static function newFromSource(\Jcupitt\Vips\Source $source, string $string_options = '', array $options = []): self + { + $loader = self::findLoadSource($source); + if ($loader === null) { + throw new \Jcupitt\Vips\Exception('unable to load from source'); + } + if ($string_options !== '') { + $options = array_merge(["string_options" => $string_options], $options); + } + return \Jcupitt\Vips\VipsOperation::call($loader, null, [$source], $options); + } + /** + * Write an image to a file. + * + * @param string $name The file to write the image to. + * @param array $options Any options to pass on to the selected save + * operation. + * + * @throws Exception + * + * @return void + */ + public function writeToFile(string $name, array $options = []): void + { + $filename = \Jcupitt\Vips\Utils::filenameGetFilename($name); + $string_options = \Jcupitt\Vips\Utils::filenameGetOptions($name); + $saver = \Jcupitt\Vips\FFI::vips()->vips_foreign_find_save($filename); + if ($saver == "") { + throw new \Jcupitt\Vips\Exception(); + } + if (strlen($string_options) != 0) { + $options = array_merge(["string_options" => $string_options], $options); + } + $result = \Jcupitt\Vips\VipsOperation::call($saver, $this, [$filename], $options); + if ($result === -1) { + throw new \Jcupitt\Vips\Exception(); + } + } + /** + * Write an image to a formatted string. + * + * @param string $suffix The file type suffix, eg. ".jpg". + * @param array $options Any options to pass on to the selected save + * operation. + * + * @throws Exception + * + * @return string The formatted image. + */ + public function writeToBuffer(string $suffix, array $options = []): string + { + $filename = \Jcupitt\Vips\Utils::filenameGetFilename($suffix); + $string_options = \Jcupitt\Vips\Utils::filenameGetOptions($suffix); + $saver = null; + // see if we can save with the Target API ... we need 8.9 or later for + // Target, and we need this libvips to have a target saver for this + // format + if (\Jcupitt\Vips\FFI::atLeast(8, 9)) { + \Jcupitt\Vips\FFI::vips()->vips_error_freeze(); + $saver = \Jcupitt\Vips\FFI::vips()->vips_foreign_find_save_target($filename); + \Jcupitt\Vips\FFI::vips()->vips_error_thaw(); + } + if ($saver !== null) { + $target = \Jcupitt\Vips\Target::newToMemory(); + if (strlen($string_options) != 0) { + $options = array_merge(["string_options" => $string_options], $options); + } + \Jcupitt\Vips\VipsOperation::call($saver, $this, [$target], $options); + $buffer = $target->get("blob"); + } else { + // fall back to the old _buffer API + $saver = \Jcupitt\Vips\FFI::vips()->vips_foreign_find_save_buffer($filename); + if ($saver == "") { + throw new \Jcupitt\Vips\Exception(); + } + if (strlen($string_options) != 0) { + $options = array_merge(["string_options" => $string_options], $options); + } + $buffer = \Jcupitt\Vips\VipsOperation::call($saver, $this, [], $options); + } + return $buffer; + } + /** + * Write an image to a large memory array. + * + * @throws Exception + * + * @return string The memory array. + */ + public function writeToMemory(): string + { + $p_size = \Jcupitt\Vips\FFI::vips()->new("size_t[1]"); + $pointer = \Jcupitt\Vips\FFI::vips()->vips_image_write_to_memory($this->pointer, $p_size); + if ($pointer == null) { + throw new \Jcupitt\Vips\Exception(); + } + // string() takes a copy + $result = \FFI::string($pointer, $p_size[0]); + \Jcupitt\Vips\FFI::glib()->g_free($pointer); + return $result; + } + /** + * Write an image to a PHP array. + * + * Pixels are written as a simple one-dimensional array, for example, if + * you write: + * + * ```php + * $result = $image->crop(100, 100, 10, 1)->writeToArray(); + * ``` + * + * This will crop out 10 pixels and write them to the array. If `$image` + * is an RGB image, then `$array` will contain 30 numbers, with the first + * three being R, G and B for the first pixel. + * + * You'll need to slice and repack the array if you want more dimensions. + * + * This method is much faster than repeatedly calling `getpoint()`. It + * will use a lot of memory. + * + * @throws Exception + * + * @return array The pixel values as a PHP array. + */ + public function writeToArray(): array + { + $p_size = \Jcupitt\Vips\FFI::vips()->new("size_t[1]"); + $pointer = \Jcupitt\Vips\FFI::vips()->vips_image_write_to_memory($this->pointer, $p_size); + if ($pointer == null) { + throw new \Jcupitt\Vips\Exception(); + } + // wrap pointer up as a C array of the right type + $type_name = \Jcupitt\Vips\FFI::ftypes($this->format); + $n = $this->width * $this->height * $this->bands; + $array = \Jcupitt\Vips\FFI::vips()->cast("{$type_name}[{$n}]", $pointer); + // copy to PHP memory as a flat array + $result = []; + for ($i = 0; $i < $n; $i++) { + $result[] = $array[$i]; + } + // the vips result is not PHP memory, so we must free it + \Jcupitt\Vips\FFI::glib()->g_free($pointer); + return $result; + } + /** + * @throws Exception + */ + public function writeToTarget(\Jcupitt\Vips\Target $target, string $suffix, array $options = []): void + { + $filename = \Jcupitt\Vips\Utils::filenameGetFilename($suffix); + $string_options = \Jcupitt\Vips\Utils::filenameGetOptions($suffix); + $saver = \Jcupitt\Vips\FFI::vips()->vips_foreign_find_save_target($filename); + if ($saver === '') { + throw new \Jcupitt\Vips\Exception("can't save to target with given suffix {$filename}"); + } + if ($string_options !== '') { + $options = array_merge(["string_options" => $string_options], $options); + } + \Jcupitt\Vips\VipsOperation::call($saver, $this, [$target], $options); + } + /** + * Copy to memory. + * + * An area of memory large enough to hold the complete image is allocated, + * the image is rendered into it, and a new Image is returned which wraps + * this memory area. + * + * This is useful for ending a pipeline and starting a new random access + * one, but can obviously use a lot of memory if the image is large. + * + * @throws Exception + * + * @return Image A new Image. + */ + public function copyMemory(): \Jcupitt\Vips\Image + { + $pointer = \Jcupitt\Vips\FFI::vips()->vips_image_copy_memory($this->pointer); + if ($pointer == null) { + throw new \Jcupitt\Vips\Exception(); + } + return new \Jcupitt\Vips\Image($pointer); + } + /** + * Get any property from the underlying image. + * + * @param string $name The property name. + * + * @throws Exception + * + * @return mixed + */ + public function __get(string $name) + { + return $this->get($name); + } + /** + * Set any property on the underlying image. + * + * @param string $name The property name. + * @param mixed $value The value to set for this property. + * + * @return void + * @throws Exception + */ + public function __set(string $name, $value): void + { + $this->set($name, $value); + } + /** + * Check if the GType of a property from the underlying image exists. + * + * @param string $name The property name. + * + * @return bool + */ + public function __isset(string $name): bool + { + return $this->getType($name) != 0; + } + /** + * Get any property from the underlying image. + * + * This is handy for fields whose name + * does not match PHP's variable naming conventions, like `'exif-data'`. + * + * It will throw an exception if $name does not exist. Use Image::getType() + * to test for the existence of a field. + * + * @param string $name The property name. + * + * @throws Exception + * + * @return mixed + */ + public function get(string $name) + { + $gvalue = new \Jcupitt\Vips\GValue(); + if (\Jcupitt\Vips\FFI::vips()->vips_image_get($this->pointer, $name, $gvalue->pointer) != 0) { + throw new \Jcupitt\Vips\Exception(); + } + return $gvalue->get(); + } + /** + * Get the GType of a property from the underlying image. GTypes are + * integer type identifiers. This function will return 0 if the field does + * not exist. + * + * @param string $name The property name. + * + * @return integer + */ + public function getType(string $name): int + { + return \Jcupitt\Vips\FFI::vips()->vips_image_get_typeof($this->pointer, $name); + } + /** + * A deprecated synonym for getType(). + * + * @param string $name The property name. + * + * @return integer + */ + public function typeOf(string $name): int + { + return $this->getType($name); + } + /** + * Get the field names available for an image. + * + * @return Array + */ + public function getFields(): array + { + $str_array = \Jcupitt\Vips\FFI::vips()->vips_image_get_fields($this->pointer); + $fields = []; + for ($i = 0; $str_array[$i] != null; $i++) { + array_push($fields, \FFI::string($str_array[$i])); + } + \Jcupitt\Vips\FFI::glib()->g_free($str_array); + return $fields; + } + /** + * Get the gainmap attached to an image, or null for no gainmap. + * + * After modifying the gainmap, you'll need to use Image::set() to + * write it back to the image again under the name "gainmap", for example: + * + * ```php + * $gainmap = $image->getGainmap(); + * if ($gainmap != null) { + * $new_gainmap = $gainmap->crop(0, 0, 10, 10); + * $image = $image->copy(); + * $image->set("gainmap", $new_gainmap); + * } + * ``` + * + * @return ?Image + */ + public function getGainmap(): ?\Jcupitt\Vips\Image + { + if (\Jcupitt\Vips\FFI::atLeast(8, 18)) { + $pointer = \Jcupitt\Vips\FFI::vips()->vips_image_get_gainmap($this->pointer); + if ($pointer == null) { + return null; + } else { + return new \Jcupitt\Vips\Image($pointer); + } + } else { + return null; + } + } + /** + * Set any property on the underlying image. + * + * This is handy for fields whose name + * does not match PHP's variable naming conventions, like `'exif-data'`. + * + * @param string $name The property name. + * @param mixed $value The value to set for this property. + * + * @throws Exception + * + * @return void + */ + public function set(string $name, $value): void + { + $gvalue = new \Jcupitt\Vips\GValue(); + $gtype = $this->getType($name); + /* If this is not a known field, guess a sensible type from the value. + */ + if ($gtype == 0) { + if (is_array($value)) { + if (is_int($value[0])) { + $gtype = \Jcupitt\Vips\FFI::gtypes("VipsArrayInt"); + } elseif (is_float($value[0])) { + $gtype = \Jcupitt\Vips\FFI::gtypes("VipsArrayDouble"); + } else { + $gtype = \Jcupitt\Vips\FFI::gtypes("VipsArrayImage"); + } + } elseif (is_int($value)) { + $gtype = \Jcupitt\Vips\FFI::gtypes("gint"); + } elseif (is_float($value)) { + $gtype = \Jcupitt\Vips\FFI::gtypes("gdouble"); + } elseif (is_string($value)) { + $gtype = \Jcupitt\Vips\FFI::gtypes("VipsRefString"); + } else { + $gtype = \Jcupitt\Vips\FFI::gtypes("VipsImage"); + } + } + $gvalue->setType($gtype); + $gvalue->set($value); + \Jcupitt\Vips\FFI::vips()->vips_image_set($this->pointer, $name, $gvalue->pointer); + } + /** + * Set the type and value for any property on the underlying image. + * + * This is useful if the type of the property cannot be determined from the + * php type of the value. + * + * Pass the type name directly, or use Utils::typeFromName() to look up + * types by name. + * + * @param string|int $type The type of the property. + * @param string $name The property name. + * @param mixed $value The value to set for this property. + * + * @throws Exception + * + * @return void + */ + public function setType($type, string $name, $value): void + { + $gvalue = new \Jcupitt\Vips\GValue(); + $gvalue->setType($type); + $gvalue->set($value); + \Jcupitt\Vips\FFI::vips()->vips_image_set($this->pointer, $name, $gvalue->pointer); + } + /** + * Remove a field from the underlying image. + * + * @param string $name The property name. + * + * @throws Exception + * + * @return void + */ + public function remove(string $name): void + { + if (!\Jcupitt\Vips\FFI::vips()->vips_image_remove($this->pointer, $name)) { + throw new \Jcupitt\Vips\Exception(); + } + } + /** + * Enable progress reporting on an image. + * + * The preeval, eval and posteval signals will be emitted on the + * most-downstream image for which setProgress() was enabled. @see + * GObject::signalConnect(). + * + * @param bool $progress TRUE to enable progress reporting. + * + * @return void + */ + public function setProgress(bool $progress): void + { + \Jcupitt\Vips\FFI::vips()->vips_image_set_progress($this->pointer, $progress); + } + /** + * Makes a string-ified version of the Image. + * + * @return string + */ + public function __toString(): string + { + $array = ['width' => $this->width, 'height' => $this->height, 'bands' => $this->bands, 'format' => $this->format, 'interpretation' => $this->interpretation]; + return json_encode($array); + } + /** + * Call any vips operation as an instance method. + * + * @param string $name The thing we call. + * @param array $arguments The arguments to the thing. + * + * @throws Exception + * + * @return mixed The result. + */ + public function __call(string $name, array $arguments) + { + return \Jcupitt\Vips\VipsOperation::callBase($name, $this, $arguments); + } + /** + * Call any vips operation as a class method. + * + * @param string $name The thing we call. + * @param array $arguments The arguments to the thing. + * + * @throws Exception + * + * @return mixed The result. + */ + public static function __callStatic(string $name, array $arguments) + { + return \Jcupitt\Vips\VipsOperation::callBase($name, null, $arguments); + } + /** + * Does this image have an alpha channel? + * + * Uses colour space interpretation with number of channels to guess + * this. + * + * @return bool indicating if this image has an alpha channel. + */ + public function hasAlpha(): bool + { + return $this->bands === 2 || $this->bands === 4 && $this->interpretation !== \Jcupitt\Vips\Interpretation::CMYK || $this->bands > 4; + } + /** + * Does band exist in image. + * + * @param mixed $offset The index to fetch. + * + * @return bool true if the index exists. + */ + public function offsetExists($offset): bool + { + return $offset >= 0 && $offset <= $this->bands - 1; + } + /** + * Get band from image. + * + * @param mixed $offset The index to fetch. + * + * @throws Exception + * + * @return Image|null the extracted band or null. + */ + public function offsetGet($offset): ?\Jcupitt\Vips\Image + { + return $this->offsetExists($offset) ? $this->extract_band($offset) : null; + } + /** + * Set a band. + * + * Use `$image[1] = $other_image;' to remove band 1 from this image, + * replacing it with all the bands in `$other_image`. + * + * Use `$image[] = $other_image;' to append all the bands in `$other_image` + * to `$image`. + * + * Use `$image[-1] = $other_image;` to prepend all the bands in + * `$other_image` to `$image`. + * + * You can use constants or arrays in place of `$other_image`. Use `$image[] + * = 255;` to append a constant 255 band, for example, or `$image[1] + * = [1, 2];` to replace band 1 with two constant bands. + * + * @param int $offset The index to set. + * @param Image $value The band to insert + * + * @throws \BadMethodCallException if the offset is not integer or null + * @throws Exception + * + * @return void + */ + public function offsetSet($offset, $value): void + { + // no offset means append + if ($offset === null) { + $offset = $this->bands; + } + if (!is_int($offset)) { + throw new \BadMethodCallException('Image::offsetSet: ' . 'offset is not integer or null'); + } + // number of bands to the left and right of $value + $n_left = min($this->bands, max(0, $offset)); + $n_right = min($this->bands, max(0, $this->bands - 1 - $offset)); + $offset = $this->bands - $n_right; + // if we are setting a constant as the first element, we must expand it + // to an image, since bandjoin must have an image as the first argument + if ($n_left === 0 && !$value instanceof \Jcupitt\Vips\Image) { + $value = $this->imageize($value); + } + $components = []; + if ($n_left > 0) { + $components[] = $this->extract_band(0, ['n' => $n_left]); + } + $components[] = $value; + if ($n_right > 0) { + $components[] = $this->extract_band($offset, ['n' => $n_right]); + } + $head = array_shift($components); + $joined = $head->bandjoin($components); + /* Overwrite our pointer with the pointer from the new, joined object. + * We have to adjust the refs, yuk! + */ + $joined->ref(); + $this->unref(); + $this->pointer = $joined->pointer; + } + /** + * Remove a band from an image. + * + * @param int $offset The index to remove. + * + * @throws \BadMethodCallException if there is only one band left in + * the image + * @throws Exception + * + * @return void + */ + public function offsetUnset($offset): void + { + if (is_int($offset) && $offset >= 0 && $offset < $this->bands) { + if ($this->bands === 1) { + throw new \BadMethodCallException('Image::offsetUnset: ' . 'cannot delete final band'); + } + $components = []; + if ($offset > 0) { + $components[] = $this->extract_band(0, ['n' => $offset]); + } + if ($offset < $this->bands - 1) { + $components[] = $this->extract_band($offset + 1, ['n' => $this->bands - 1 - $offset]); + } + $head = array_shift($components); + if (empty($components)) { + $head->ref(); + $this->unref(); + $this->pointer = $head->pointer; + } else { + $new_image = $head->bandjoin($components); + $new_image->ref(); + $this->unref(); + $this->pointer = $new_image->pointer; + } + } + } + /** + * Add $other to this image. + * + * @param mixed $other The thing to add to this image. + * @param array $options An array of options to pass to the operation. + * + * @throws Exception + * + * @return Image A new image. + */ + public function add($other, array $options = []): \Jcupitt\Vips\Image + { + if (self::isImageish($other)) { + return \Jcupitt\Vips\VipsOperation::call('add', $this, [$other], $options); + } else { + return $this->linear(1, $other, $options); + } + } + /** + * Subtract $other from this image. + * + * @param mixed $other The thing to subtract from this image. + * @param array $options An array of options to pass to the operation. + * + * @throws Exception + * + * @return Image A new image. + */ + public function subtract($other, array $options = []): \Jcupitt\Vips\Image + { + if (self::isImageish($other)) { + return \Jcupitt\Vips\VipsOperation::call('subtract', $this, [$other], $options); + } else { + $other = self::mapNumeric($other, function ($value) { + return -1 * $value; + }); + return $this->linear(1, $other, $options); + } + } + /** + * Multiply this image by $other. + * + * @param mixed $other The thing to multiply this image by. + * @param array $options An array of options to pass to the operation. + * + * @throws Exception + * + * @return Image A new image. + */ + public function multiply($other, array $options = []): \Jcupitt\Vips\Image + { + if (self::isImageish($other)) { + return \Jcupitt\Vips\VipsOperation::call('multiply', $this, [$other], $options); + } else { + return $this->linear($other, 0, $options); + } + } + /** + * Divide this image by $other. + * + * @param mixed $other The thing to divide this image by. + * @param array $options An array of options to pass to the operation. + * + * @throws Exception + * + * @return Image A new image. + */ + public function divide($other, array $options = []): \Jcupitt\Vips\Image + { + if (self::isImageish($other)) { + return \Jcupitt\Vips\VipsOperation::call('divide', $this, [$other], $options); + } else { + $other = self::mapNumeric($other, function ($value) { + return $value ** -1; + }); + return $this->linear($other, 0, $options); + } + } + /** + * Remainder of this image and $other. + * + * @param mixed $other The thing to take the remainder with. + * @param array $options An array of options to pass to the operation. + * + * @throws Exception + * + * @return Image A new image. + */ + public function remainder($other, array $options = []): \Jcupitt\Vips\Image + { + if (self::isImageish($other)) { + return \Jcupitt\Vips\VipsOperation::call('remainder', $this, [$other], $options); + } else { + return \Jcupitt\Vips\VipsOperation::call('remainder_const', $this, [$other], $options); + } + } + /** + * Find $this to the power of $other. + * + * @param mixed $other The right-hand side of the operator. + * @param array $options An array of options to pass to the operation. + * + * @throws Exception + * + * @return Image A new image. + */ + public function pow($other, array $options = []): \Jcupitt\Vips\Image + { + return self::callEnum($other, 'math2', \Jcupitt\Vips\OperationMath2::POW, $options); + } + /** + * Find $other to the power of $this. + * + * @param mixed $other The right-hand side of the operator. + * @param array $options An array of options to pass to the operation. + * + * @throws Exception + * + * @return Image A new image. + */ + public function wop($other, array $options = []): \Jcupitt\Vips\Image + { + return self::callEnum($other, 'math2', \Jcupitt\Vips\OperationMath2::WOP, $options); + } + /** + * Shift $this left by $other. + * + * @param mixed $other The right-hand side of the operator. + * @param array $options An array of options to pass to the operation. + * + * @throws Exception + * + * @return Image A new image. + */ + public function lshift($other, array $options = []): \Jcupitt\Vips\Image + { + return self::callEnum($other, 'boolean', \Jcupitt\Vips\OperationBoolean::LSHIFT, $options); + } + /** + * Shift $this right by $other. + * + * @param mixed $other The right-hand side of the operator. + * @param array $options An array of options to pass to the operation. + * + * @throws Exception + * + * @return Image A new image. + */ + public function rshift($other, array $options = []): \Jcupitt\Vips\Image + { + return self::callEnum($other, 'boolean', \Jcupitt\Vips\OperationBoolean::RSHIFT, $options); + } + /** + * Bitwise AND of $this and $other. This has to be called ->andimage() + * rather than ->and() to avoid confusion in phpdoc. + * + * @param mixed $other The right-hand side of the operator. + * @param array $options An array of options to pass to the operation. + * + * @throws Exception + * + * @return Image A new image. + */ + public function andimage($other, array $options = []): \Jcupitt\Vips\Image + { + // phpdoc hates OperationBoolean::AND, so use the string form here + return self::callEnum($other, 'boolean', 'and', $options); + } + /** + * Bitwise OR of $this and $other. + * + * @param mixed $other The right-hand side of the operator. + * @param array $options An array of options to pass to the operation. + * + * @throws Exception + * + * @return Image A new image. + */ + public function orimage($other, array $options = []): \Jcupitt\Vips\Image + { + // phpdoc hates OperationBoolean::OR, so use the string form here + return self::callEnum($other, 'boolean', 'or', $options); + } + /** + * Bitwise EOR of $this and $other. + * + * @param mixed $other The right-hand side of the operator. + * @param array $options An array of options to pass to the operation. + * + * @throws Exception + * + * @return Image A new image. + */ + public function eorimage($other, array $options = []): \Jcupitt\Vips\Image + { + return self::callEnum($other, 'boolean', \Jcupitt\Vips\OperationBoolean::EOR, $options); + } + /** + * 255 where $this is more than $other. + * + * @param mixed $other The right-hand side of the operator. + * @param array $options An array of options to pass to the operation. + * + * @throws Exception + * + * @return Image A new image. + */ + public function more($other, array $options = []): \Jcupitt\Vips\Image + { + return self::callEnum($other, 'relational', \Jcupitt\Vips\OperationRelational::MORE, $options); + } + /** + * 255 where $this is more than or equal to $other. + * + * @param mixed $other The right-hand side of the operator. + * @param array $options An array of options to pass to the operation. + * + * @throws Exception + * + * @return Image A new image. + */ + public function moreEq($other, array $options = []): \Jcupitt\Vips\Image + { + return self::callEnum($other, 'relational', \Jcupitt\Vips\OperationRelational::MOREEQ, $options); + } + /** + * 255 where $this is less than $other. + * + * @param mixed $other The right-hand side of the operator. + * @param array $options An array of options to pass to the operation. + * + * @throws Exception + * + * @return Image A new image. + */ + public function less($other, array $options = []): \Jcupitt\Vips\Image + { + return self::callEnum($other, 'relational', \Jcupitt\Vips\OperationRelational::LESS, $options); + } + /** + * 255 where $this is less than or equal to $other. + * + * @param mixed $other The right-hand side of the operator. + * @param array $options An array of options to pass to the operation. + * + * @throws Exception + * + * @return Image A new image. + */ + public function lessEq($other, array $options = []): \Jcupitt\Vips\Image + { + return self::callEnum($other, 'relational', \Jcupitt\Vips\OperationRelational::LESSEQ, $options); + } + /** + * 255 where $this is equal to $other. + * + * @param mixed $other The right-hand side of the operator. + * @param array $options An array of options to pass to the operation. + * + * @throws Exception + * + * @return Image A new image. + */ + public function equal($other, array $options = []): \Jcupitt\Vips\Image + { + return self::callEnum($other, 'relational', \Jcupitt\Vips\OperationRelational::EQUAL, $options); + } + /** + * 255 where $this is not equal to $other. + * + * @param mixed $other The right-hand side of the operator. + * @param array $options An array of options to pass to the operation. + * + * @throws Exception + * + * @return Image A new image. + */ + public function notEq($other, array $options = []): \Jcupitt\Vips\Image + { + return self::callEnum($other, 'relational', \Jcupitt\Vips\OperationRelational::NOTEQ, $options); + } + /** + * Join $this and $other bandwise. + * + * @param mixed $other The right-hand side of the operator. + * @param array $options An array of options to pass to the operation. + * + * @throws Exception + * + * @return Image A new image. + */ + public function bandjoin($other, array $options = []): \Jcupitt\Vips\Image + { + /* Allow a single unarrayed value as well. + */ + if ($other instanceof \Jcupitt\Vips\Image) { + $other = [$other]; + } else { + $other = (array) $other; + } + /* If $other is all numbers, we can use self::bandjoin_const(). + */ + $is_const = \true; + foreach ($other as $item) { + if (!is_numeric($item)) { + $is_const = \false; + break; + } + } + /* We can't use self::bandjoin(), that would just recurse. + */ + if ($is_const) { + return \Jcupitt\Vips\VipsOperation::call('bandjoin_const', $this, [$other], $options); + } else { + return \Jcupitt\Vips\VipsOperation::call('bandjoin', null, [array_merge([$this], $other)], $options); + } + } + /** + * Split $this into an array of single-band images. + * + * @param array $options An array of options to pass to the operation. + * + * @throws Exception + * + * @return array An array of images. + */ + public function bandsplit(array $options = []): array + { + $result = []; + for ($i = 0; $i < $this->bands; $i++) { + $result[] = $this->extract_band($i, $options); + } + return $result; + } + /** + * For each band element, sort the array of input images and pick the + * median. Use the index option to pick something else. + * + * @param mixed $other The right-hand side of the operator. + * @param array $options An array of options to pass to the operation. + * + * @throws Exception + * + * @return Image A new image. + */ + public function bandrank($other, array $options = []): \Jcupitt\Vips\Image + { + /* bandrank will appear as a static class member, as + * Image::bandrank([a, b, c]), but it's better as an instance + * method. + * + * We need to define this by hand. + */ + /* Allow a single unarrayed value as well. + */ + if ($other instanceof \Jcupitt\Vips\Image) { + $other = [$other]; + } else { + $other = (array) $other; + } + return \Jcupitt\Vips\VipsOperation::call('bandrank', null, [array_merge([$this], $other)], $options); + } + /** + * Composite $other on top of $this with $mode. + * + * @param mixed $other The overlay. + * @param BlendMode|array $mode The mode to composite with. + * @param array $options An array of options to pass to the operation. + * + * @throws Exception + * + * @return Image A new image. + */ + public function composite($other, $mode, array $options = []): \Jcupitt\Vips\Image + { + /* Allow a single unarrayed value as well. + */ + if ($other instanceof \Jcupitt\Vips\Image) { + $other = [$other]; + } else { + $other = (array) $other; + } + if (!is_array($mode)) { + $mode = [$mode]; + } + # composite takes an arrayint, but it's really an array of blend modes + # gvalue doesn't know this, so we must do name -> enum value mapping + $mode = array_map(function ($x) { + return \Jcupitt\Vips\GValue::toEnum(\Jcupitt\Vips\FFI::gtypes("VipsBlendMode"), $x); + }, $mode); + return \Jcupitt\Vips\VipsOperation::call('composite', null, [array_merge([$this], $other), $mode], $options); + } + /** + * Position of max is awkward with plain self::max. + * + * @throws Exception + * + * @return array (float, int, int) The value and position of the maximum. + */ + public function maxpos(): array + { + $result = $this->max(['x' => \true, 'y' => \true]); + $out = $result['out']; + $x = $result['x']; + $y = $result['y']; + return [$out, $x, $y]; + } + /** + * Position of min is awkward with plain self::max. + * + * @throws Exception + * + * @return array (float, int, int) The value and position of the minimum. + */ + public function minpos(): array + { + $result = $this->min(['x' => \true, 'y' => \true]); + $out = $result['out']; + $x = $result['x']; + $y = $result['y']; + return [$out, $x, $y]; + } + /** + * Use $this as a condition image to pick pixels from either $then or + * $else. + * + * @param mixed $then The true side of the operator + * @param mixed $else The false side of the operator. + * @param array $options An array of options to pass to the operation. + * + * @throws Exception + * + * @return Image A new image. + */ + public function ifthenelse($then, $else, array $options = []): \Jcupitt\Vips\Image + { + /* We need different imageize rules for this. We need $then and $else to + * match each other first, and only if they are both constants do we + * match to $this. + */ + $match_image = null; + foreach ([$then, $else, $this] as $item) { + if ($item instanceof \Jcupitt\Vips\Image) { + $match_image = $item; + break; + } + } + if (!$then instanceof \Jcupitt\Vips\Image) { + $then = $match_image->imageize($then); + } + if (!$else instanceof \Jcupitt\Vips\Image) { + $else = $match_image->imageize($else); + } + return \Jcupitt\Vips\VipsOperation::call('ifthenelse', $this, [$then, $else], $options); + } + /** + * Return the largest integral value not greater than the argument. + * + * @throws Exception + * + * @return Image A new image. + */ + public function floor(): \Jcupitt\Vips\Image + { + return $this->round(\Jcupitt\Vips\OperationRound::FLOOR); + } + /** + * Return the smallest integral value not less than the argument. + * + * @throws Exception + * + * @return Image A new image. + */ + public function ceil(): \Jcupitt\Vips\Image + { + return $this->round(\Jcupitt\Vips\OperationRound::CEIL); + } + /** + * Return the nearest integral value. + * + * @throws Exception + * + * @return Image A new image. + */ + public function rint(): \Jcupitt\Vips\Image + { + return $this->round(\Jcupitt\Vips\OperationRound::RINT); + } + /** + * AND image bands together. + * + * @throws Exception + * + * @return Image A new image. + */ + public function bandand(): \Jcupitt\Vips\Image + { + // phpdoc hates OperationBoolean::AND, so use the string form here + return $this->bandbool('and'); + } + /** + * OR image bands together. + * + * @throws Exception + * + * @return Image A new image. + */ + public function bandor(): \Jcupitt\Vips\Image + { + // phpdoc hates OperationBoolean::OR, so use the string form here + return $this->bandbool('or'); + } + /** + * EOR image bands together. + * + * @throws Exception + * + * @return Image A new image. + */ + public function bandeor(): \Jcupitt\Vips\Image + { + return $this->bandbool(\Jcupitt\Vips\OperationBoolean::EOR); + } + /** + * Return the real part of a complex image. + * + * @throws Exception + * + * @return Image A new image. + */ + public function real(): \Jcupitt\Vips\Image + { + return $this->complexget(\Jcupitt\Vips\OperationComplexget::REAL); + } + /** + * Return the imaginary part of a complex image. + * + * @throws Exception + * + * @return Image A new image. + */ + public function imag(): \Jcupitt\Vips\Image + { + return $this->complexget(\Jcupitt\Vips\OperationComplexget::IMAG); + } + /** + * Return an image converted to polar coordinates. + * + * @throws Exception + * + * @return Image A new image. + */ + public function polar(): \Jcupitt\Vips\Image + { + return self::runCmplx(function ($image) { + return $image->complex(\Jcupitt\Vips\OperationComplex::POLAR); + }, $this); + } + /** + * Return an image converted to rectangular coordinates. + * + * @throws Exception + * + * @return Image A new image. + */ + public function rect(): \Jcupitt\Vips\Image + { + return self::runCmplx(function ($image) { + return $image->complex(\Jcupitt\Vips\OperationComplex::RECT); + }, $this); + } + /** + * Return the complex conjugate of an image. + * + * @throws Exception + * + * @return Image A new image. + */ + public function conj(): \Jcupitt\Vips\Image + { + return $this->complex(\Jcupitt\Vips\OperationComplex::CONJ); + } + /** + * Find the cross-phase of this image with $other. + * + * @param mixed $other The thing to cross-phase by. + * + * @throws Exception + * + * @return Image A new image. + */ + public function crossPhase($other): \Jcupitt\Vips\Image + { + return $this->complex2($other, \Jcupitt\Vips\OperationComplex2::CROSS_PHASE); + } + /** + * Return the sine of an image in degrees. + * + * @throws Exception + * + * @return Image A new image. + */ + public function sin(): \Jcupitt\Vips\Image + { + return $this->math(\Jcupitt\Vips\OperationMath::SIN); + } + /** + * Return the cosine of an image in degrees. + * + * @throws Exception + * + * @return Image A new image. + */ + public function cos(): \Jcupitt\Vips\Image + { + return $this->math(\Jcupitt\Vips\OperationMath::COS); + } + /** + * Return the tangent of an image in degrees. + * + * @throws Exception + * + * @return Image A new image. + */ + public function tan(): \Jcupitt\Vips\Image + { + return $this->math(\Jcupitt\Vips\OperationMath::TAN); + } + /** + * Return the inverse sine of an image in degrees. + * + * @throws Exception + * + * @return Image A new image. + */ + public function asin(): \Jcupitt\Vips\Image + { + return $this->math(\Jcupitt\Vips\OperationMath::ASIN); + } + /** + * Return the inverse cosine of an image in degrees. + * + * @throws Exception + * + * @return Image A new image. + */ + public function acos(): \Jcupitt\Vips\Image + { + return $this->math(\Jcupitt\Vips\OperationMath::ACOS); + } + /** + * Return the inverse tangent of an image in degrees. + * + * @throws Exception + * + * @return Image A new image. + */ + public function atan(): \Jcupitt\Vips\Image + { + return $this->math(\Jcupitt\Vips\OperationMath::ATAN); + } + /** + * Return the natural log of an image. + * + * @throws Exception + * + * @return Image A new image. + */ + public function log(): \Jcupitt\Vips\Image + { + return $this->math(\Jcupitt\Vips\OperationMath::LOG); + } + /** + * Return the log base 10 of an image. + * + * @throws Exception + * + * @return Image A new image. + */ + public function log10(): \Jcupitt\Vips\Image + { + return $this->math(\Jcupitt\Vips\OperationMath::LOG10); + } + /** + * Return e ** pixel. + * + * @throws Exception + * + * @return Image A new image. + */ + public function exp(): \Jcupitt\Vips\Image + { + return $this->math(\Jcupitt\Vips\OperationMath::EXP); + } + /** + * Return 10 ** pixel. + * + * @throws Exception + * + * @return Image A new image. + */ + public function exp10(): \Jcupitt\Vips\Image + { + return $this->math(\Jcupitt\Vips\OperationMath::EXP10); + } + /** + * Erode with a structuring element. + * + * @param mixed $mask Erode with this structuring element. + * + * @throws Exception + * + * @return Image A new image. + */ + public function erode($mask): \Jcupitt\Vips\Image + { + return $this->morph($mask, \Jcupitt\Vips\OperationMorphology::ERODE); + } + /** + * Dilate with a structuring element. + * + * @param mixed $mask Dilate with this structuring element. + * + * @throws Exception + * + * @return Image A new image. + */ + public function dilate($mask): \Jcupitt\Vips\Image + { + return $this->morph($mask, \Jcupitt\Vips\OperationMorphology::DILATE); + } + /** + * $size x $size median filter. + * + * @param int $size Size of median filter. + * + * @throws Exception + * + * @return Image A new image. + */ + public function median(int $size): \Jcupitt\Vips\Image + { + return $this->rank($size, $size, $size * $size / 2); + } + /** + * Flip horizontally. + * + * @throws Exception + * + * @return Image A new image. + */ + public function fliphor(): \Jcupitt\Vips\Image + { + return $this->flip(\Jcupitt\Vips\Direction::HORIZONTAL); + } + /** + * Flip vertically. + * + * @throws Exception + * + * @return Image A new image. + */ + public function flipver(): \Jcupitt\Vips\Image + { + return $this->flip(\Jcupitt\Vips\Direction::VERTICAL); + } + /** + * Rotate 90 degrees clockwise. + * + * @throws Exception + * + * @return Image A new image. + */ + public function rot90(): \Jcupitt\Vips\Image + { + return $this->rot(\Jcupitt\Vips\Angle::D90); + } + /** + * Rotate 180 degrees. + * + * @throws Exception + * + * @return Image A new image. + */ + public function rot180(): \Jcupitt\Vips\Image + { + return $this->rot(\Jcupitt\Vips\Angle::D180); + } + /** + * Rotate 270 degrees clockwise. + * + * @throws Exception + * + * @return Image A new image. + */ + public function rot270(): \Jcupitt\Vips\Image + { + return $this->rot(\Jcupitt\Vips\Angle::D270); + } +} +/* + * Local variables: + * tab-width: 4 + * c-basic-offset: 4 + * End: + * vim600: expandtab sw=4 ts=4 fdm=marker + * vim<600: expandtab sw=4 ts=4 + */ diff --git a/src/wp-includes/php-vips/src/ImageAutodoc.php b/src/wp-includes/php-vips/src/ImageAutodoc.php new file mode 100644 index 0000000000000..a89ebd163f40f --- /dev/null +++ b/src/wp-includes/php-vips/src/ImageAutodoc.php @@ -0,0 +1,758 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * Autodocs for the Image class. + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + * + * @method Image CMC2LCh(array $options = []) Transform LCh to CMC. + * @throws Exception + * @method Image CMYK2XYZ(array $options = []) Transform CMYK to XYZ. + * @throws Exception + * @method Image HSV2sRGB(array $options = []) Transform HSV to sRGB. + * @throws Exception + * @method Image LCh2CMC(array $options = []) Transform LCh to CMC. + * @throws Exception + * @method Image LCh2Lab(array $options = []) Transform LCh to Lab. + * @throws Exception + * @method Image Lab2LCh(array $options = []) Transform Lab to LCh. + * @throws Exception + * @method Image Lab2LabQ(array $options = []) Transform float Lab to LabQ coding. + * @throws Exception + * @method Image Lab2LabS(array $options = []) Transform float Lab to signed short. + * @throws Exception + * @method Image Lab2XYZ(array $options = []) Transform CIELAB to XYZ. + * @throws Exception + * @method Image LabQ2Lab(array $options = []) Unpack a LabQ image to float Lab. + * @throws Exception + * @method Image LabQ2LabS(array $options = []) Unpack a LabQ image to short Lab. + * @throws Exception + * @method Image LabQ2sRGB(array $options = []) Convert a LabQ image to sRGB. + * @throws Exception + * @method Image LabS2Lab(array $options = []) Transform signed short Lab to float. + * @throws Exception + * @method Image LabS2LabQ(array $options = []) Transform short Lab to LabQ coding. + * @throws Exception + * @method Image Oklab2Oklch(array $options = []) Transform Oklab to Oklch. + * @throws Exception + * @method Image Oklab2XYZ(array $options = []) Transform Oklab to XYZ. + * @throws Exception + * @method Image Oklch2Oklab(array $options = []) Transform Oklch to Oklab. + * @throws Exception + * @method Image XYZ2CMYK(array $options = []) Transform XYZ to CMYK. + * @throws Exception + * @method Image XYZ2Lab(array $options = []) Transform XYZ to Lab. + * @throws Exception + * @method Image XYZ2Oklab(array $options = []) Transform XYZ to Oklab. + * @throws Exception + * @method Image XYZ2Yxy(array $options = []) Transform XYZ to Yxy. + * @throws Exception + * @method Image XYZ2scRGB(array $options = []) Transform XYZ to scRGB. + * @throws Exception + * @method Image Yxy2XYZ(array $options = []) Transform Yxy to XYZ. + * @throws Exception + * @method Image abs(array $options = []) Absolute value of an image. + * @throws Exception + * @method Image addalpha(array $options = []) Append an alpha channel. + * @throws Exception + * @method Image affine(float[]|float $matrix, array $options = []) Affine transform of an image. + * @throws Exception + * @method static Image analyzeload(string $filename, array $options = []) Load an Analyze6 image. + * @throws Exception + * @method static Image arrayjoin(Image[]|Image $in, array $options = []) Join an array of images. + * @throws Exception + * @method Image autorot(array $options = []) Autorotate image by exif tag. + * @throws Exception + * @method float avg(array $options = []) Find image average. + * @throws Exception + * @method Image bandbool(string $boolean, array $options = []) Boolean operation across image bands. + * @see OperationBoolean for possible values for $boolean + * @throws Exception + * @method Image bandfold(array $options = []) Fold up x axis into bands. + * @throws Exception + * @method Image bandjoin_const(float[]|float $c, array $options = []) Append a constant band to an image. + * @throws Exception + * @method Image bandmean(array $options = []) Band-wise average. + * @throws Exception + * @method Image bandunfold(array $options = []) Unfold image bands into x axis. + * @throws Exception + * @method static Image black(integer $width, integer $height, array $options = []) Make a black image. + * @throws Exception + * @method Image boolean(Image $right, string $boolean, array $options = []) Boolean operation on two images. + * @see OperationBoolean for possible values for $boolean + * @throws Exception + * @method Image boolean_const(string $boolean, float[]|float $c, array $options = []) Boolean operations against a constant. + * @see OperationBoolean for possible values for $boolean + * @throws Exception + * @method Image buildlut(array $options = []) Build a look-up table. + * @throws Exception + * @method Image byteswap(array $options = []) Byteswap an image. + * @throws Exception + * @method Image canny(array $options = []) Canny edge detector. + * @throws Exception + * @method Image case(Image[]|Image $cases, array $options = []) Use pixel values to pick cases from an array of images. + * @throws Exception + * @method Image cast(string $format, array $options = []) Cast an image. + * @see BandFormat for possible values for $format + * @throws Exception + * @method Image clamp(array $options = []) Clamp values of an image. + * @throws Exception + * @method Image colourspace(string $space, array $options = []) Convert to a new colorspace. + * @see Interpretation for possible values for $space + * @throws Exception + * @method Image compass(Image $mask, array $options = []) Convolve with rotating mask. + * @throws Exception + * @method Image complex(string $cmplx, array $options = []) Perform a complex operation on an image. + * @see OperationComplex for possible values for $cmplx + * @throws Exception + * @method Image complex2(Image $right, string $cmplx, array $options = []) Complex binary operations on two images. + * @see OperationComplex2 for possible values for $cmplx + * @throws Exception + * @method Image complexform(Image $right, array $options = []) Form a complex image from two real images. + * @throws Exception + * @method Image complexget(string $get, array $options = []) Get a component from a complex image. + * @see OperationComplexget for possible values for $get + * @throws Exception + * @method Image composite2(Image $overlay, string $mode, array $options = []) Blend a pair of images with a blend mode. + * @see BlendMode for possible values for $mode + * @throws Exception + * @method Image conv(Image $mask, array $options = []) Convolution operation. + * @throws Exception + * @method Image conva(Image $mask, array $options = []) Approximate integer convolution. + * @throws Exception + * @method Image convasep(Image $mask, array $options = []) Approximate separable integer convolution. + * @throws Exception + * @method Image convf(Image $mask, array $options = []) Float convolution operation. + * @throws Exception + * @method Image convi(Image $mask, array $options = []) Int convolution operation. + * @throws Exception + * @method Image convsep(Image $mask, array $options = []) Separable convolution operation. + * @throws Exception + * @method Image copy(array $options = []) Copy an image. + * @throws Exception + * @method float countlines(string $direction, array $options = []) Count lines in an image. + * @see Direction for possible values for $direction + * @throws Exception + * @method Image crop(integer $left, integer $top, integer $width, integer $height, array $options = []) Extract an area from an image. + * @throws Exception + * @method static Image csvload(string $filename, array $options = []) Load csv. + * @throws Exception + * @method static Image csvload_source(Source $source, array $options = []) Load csv. + * @throws Exception + * @method void csvsave(string $filename, array $options = []) Save image to csv. + * @throws Exception + * @method void csvsave_target(Target $target, array $options = []) Save image to csv. + * @throws Exception + * @method Image dE00(Image $right, array $options = []) Calculate dE00. + * @throws Exception + * @method Image dE76(Image $right, array $options = []) Calculate dE76. + * @throws Exception + * @method Image dECMC(Image $right, array $options = []) Calculate dECMC. + * @throws Exception + * @method static Image dcrawload(string $filename, array $options = []) Load RAW camera files. + * @throws Exception + * @method static Image dcrawload_buffer(string $buffer, array $options = []) Load RAW camera files. + * @throws Exception + * @method static Image dcrawload_source(Source $source, array $options = []) Load RAW camera files. + * @throws Exception + * @method float deviate(array $options = []) Find image standard deviation. + * @throws Exception + * @method Image draw_circle(float[]|float $ink, integer $cx, integer $cy, integer $radius, array $options = []) Draw a circle on an image. + * @throws Exception + * @method Image draw_flood(float[]|float $ink, integer $x, integer $y, array $options = []) Flood-fill an area. + * @throws Exception + * @method Image draw_image(Image $sub, integer $x, integer $y, array $options = []) Paint an image into another image. + * @throws Exception + * @method Image draw_line(float[]|float $ink, integer $x1, integer $y1, integer $x2, integer $y2, array $options = []) Draw a line on an image. + * @throws Exception + * @method Image draw_mask(float[]|float $ink, Image $mask, integer $x, integer $y, array $options = []) Draw a mask on an image. + * @throws Exception + * @method Image draw_rect(float[]|float $ink, integer $left, integer $top, integer $width, integer $height, array $options = []) Paint a rectangle on an image. + * @throws Exception + * @method Image draw_smudge(integer $left, integer $top, integer $width, integer $height, array $options = []) Blur a rectangle on an image. + * @throws Exception + * @method void dzsave(string $filename, array $options = []) Save image to deepzoom file. + * @throws Exception + * @method string dzsave_buffer(array $options = []) Save image to dz buffer. + * @throws Exception + * @method void dzsave_target(Target $target, array $options = []) Save image to deepzoom target. + * @throws Exception + * @method Image embed(integer $x, integer $y, integer $width, integer $height, array $options = []) Embed an image in a larger image. + * @throws Exception + * @method Image extract_area(integer $left, integer $top, integer $width, integer $height, array $options = []) Extract an area from an image. + * @throws Exception + * @method Image extract_band(integer $band, array $options = []) Extract band from an image. + * @throws Exception + * @method static Image eye(integer $width, integer $height, array $options = []) Make an image showing the eye's spatial response. + * @throws Exception + * @method Image falsecolour(array $options = []) False-color an image. + * @throws Exception + * @method Image fastcor(Image $ref, array $options = []) Fast correlation. + * @throws Exception + * @method Image fill_nearest(array $options = []) Fill image zeros with nearest non-zero pixel. + * @throws Exception + * @method array find_trim(array $options = []) Search an image for non-edge areas. + * Return array with: [ + * 'left' => @type integer Left edge of image + * 'top' => @type integer Top edge of extract area + * 'width' => @type integer Width of extract area + * 'height' => @type integer Height of extract area + * ]; + * @throws Exception + * @method static Image fitsload(string $filename, array $options = []) Load a FITS image. + * @throws Exception + * @method static Image fitsload_source(Source $source, array $options = []) Load FITS from a source. + * @throws Exception + * @method void fitssave(string $filename, array $options = []) Save image to fits file. + * @throws Exception + * @method Image flatten(array $options = []) Flatten alpha out of an image. + * @throws Exception + * @method Image flip(string $direction, array $options = []) Flip an image. + * @see Direction for possible values for $direction + * @throws Exception + * @method Image float2rad(array $options = []) Transform float RGB to Radiance coding. + * @throws Exception + * @method static Image fractsurf(integer $width, integer $height, float $fractal_dimension, array $options = []) Make a fractal surface. + * @throws Exception + * @method Image freqmult(Image $mask, array $options = []) Frequency-domain filtering. + * @throws Exception + * @method Image fwfft(array $options = []) Forward FFT. + * @throws Exception + * @method Image gamma(array $options = []) Gamma an image. + * @throws Exception + * @method Image gaussblur(float $sigma, array $options = []) Gaussian blur. + * @throws Exception + * @method static Image gaussmat(float $sigma, float $min_ampl, array $options = []) Make a gaussian image. + * @throws Exception + * @method static Image gaussnoise(integer $width, integer $height, array $options = []) Make a gaussnoise image. + * @throws Exception + * @method array getpoint(integer $x, integer $y, array $options = []) Read a point from an image. + * @throws Exception + * @method static Image gifload(string $filename, array $options = []) Load GIF with libnsgif. + * @throws Exception + * @method static Image gifload_buffer(string $buffer, array $options = []) Load GIF with libnsgif. + * @throws Exception + * @method static Image gifload_source(Source $source, array $options = []) Load gif from source. + * @throws Exception + * @method void gifsave(string $filename, array $options = []) Save as gif. + * @throws Exception + * @method string gifsave_buffer(array $options = []) Save as gif. + * @throws Exception + * @method void gifsave_target(Target $target, array $options = []) Save as gif. + * @throws Exception + * @method Image globalbalance(array $options = []) Global balance an image mosaic. + * @throws Exception + * @method Image gravity(string $direction, integer $width, integer $height, array $options = []) Place an image within a larger image with a certain gravity. + * @see CompassDirection for possible values for $direction + * @throws Exception + * @method static Image grey(integer $width, integer $height, array $options = []) Make a grey ramp image. + * @throws Exception + * @method Image grid(integer $tile_height, integer $across, integer $down, array $options = []) Grid an image. + * @throws Exception + * @method static Image heifload(string $filename, array $options = []) Load a HEIF image. + * @throws Exception + * @method static Image heifload_buffer(string $buffer, array $options = []) Load a HEIF image. + * @throws Exception + * @method static Image heifload_source(Source $source, array $options = []) Load a HEIF image. + * @throws Exception + * @method void heifsave(string $filename, array $options = []) Save image in HEIF format. + * @throws Exception + * @method string heifsave_buffer(array $options = []) Save image in HEIF format. + * @throws Exception + * @method void heifsave_target(Target $target, array $options = []) Save image in HEIF format. + * @throws Exception + * @method Image hist_cum(array $options = []) Form cumulative histogram. + * @throws Exception + * @method float hist_entropy(array $options = []) Estimate image entropy. + * @throws Exception + * @method Image hist_equal(array $options = []) Histogram equalisation. + * @throws Exception + * @method Image hist_find(array $options = []) Find image histogram. + * @throws Exception + * @method Image hist_find_indexed(Image $index, array $options = []) Find indexed image histogram. + * @throws Exception + * @method Image hist_find_ndim(array $options = []) Find n-dimensional image histogram. + * @throws Exception + * @method bool hist_ismonotonic(array $options = []) Test for monotonicity. + * @throws Exception + * @method Image hist_local(integer $width, integer $height, array $options = []) Local histogram equalisation. + * @throws Exception + * @method Image hist_match(Image $ref, array $options = []) Match two histograms. + * @throws Exception + * @method Image hist_norm(array $options = []) Normalise histogram. + * @throws Exception + * @method Image hist_plot(array $options = []) Plot histogram. + * @throws Exception + * @method Image hough_circle(array $options = []) Find hough circle transform. + * @throws Exception + * @method Image hough_line(array $options = []) Find hough line transform. + * @throws Exception + * @method Image icc_export(array $options = []) Output to device with ICC profile. + * @throws Exception + * @method Image icc_import(array $options = []) Import from device with ICC profile. + * @throws Exception + * @method Image icc_transform(string $output_profile, array $options = []) Transform between devices with ICC profiles. + * @throws Exception + * @method static Image identity(array $options = []) Make a 1D image where pixel values are indexes. + * @throws Exception + * @method Image insert(Image $sub, integer $x, integer $y, array $options = []) Insert image @sub into @main at @x, @y. + * @throws Exception + * @method Image invert(array $options = []) Invert an image. + * @throws Exception + * @method Image invertlut(array $options = []) Build an inverted look-up table. + * @throws Exception + * @method Image invfft(array $options = []) Inverse FFT. + * @throws Exception + * @method Image join(Image $in2, string $direction, array $options = []) Join a pair of images. + * @see Direction for possible values for $direction + * @throws Exception + * @method static Image jp2kload(string $filename, array $options = []) Load JPEG2000 image. + * @throws Exception + * @method static Image jp2kload_buffer(string $buffer, array $options = []) Load JPEG2000 image. + * @throws Exception + * @method static Image jp2kload_source(Source $source, array $options = []) Load JPEG2000 image. + * @throws Exception + * @method void jp2ksave(string $filename, array $options = []) Save image in JPEG2000 format. + * @throws Exception + * @method string jp2ksave_buffer(array $options = []) Save image in JPEG2000 format. + * @throws Exception + * @method void jp2ksave_target(Target $target, array $options = []) Save image in JPEG2000 format. + * @throws Exception + * @method static Image jpegload(string $filename, array $options = []) Load jpeg from file. + * @throws Exception + * @method static Image jpegload_buffer(string $buffer, array $options = []) Load jpeg from buffer. + * @throws Exception + * @method static Image jpegload_source(Source $source, array $options = []) Load image from jpeg source. + * @throws Exception + * @method void jpegsave(string $filename, array $options = []) Save as jpeg. + * @throws Exception + * @method string jpegsave_buffer(array $options = []) Save as jpeg. + * @throws Exception + * @method void jpegsave_mime(array $options = []) Save image to jpeg mime. + * @throws Exception + * @method void jpegsave_target(Target $target, array $options = []) Save as jpeg. + * @throws Exception + * @method static Image jxlload(string $filename, array $options = []) Load JPEG-XL image. + * @throws Exception + * @method static Image jxlload_buffer(string $buffer, array $options = []) Load JPEG-XL image. + * @throws Exception + * @method static Image jxlload_source(Source $source, array $options = []) Load JPEG-XL image. + * @throws Exception + * @method void jxlsave(string $filename, array $options = []) Save image in JPEG-XL format. + * @throws Exception + * @method string jxlsave_buffer(array $options = []) Save image in JPEG-XL format. + * @throws Exception + * @method void jxlsave_target(Target $target, array $options = []) Save image in JPEG-XL format. + * @throws Exception + * @method Image labelregions(array $options = []) Label regions in an image. + * @throws Exception + * @method Image linear(float[]|float $a, float[]|float $b, array $options = []) Calculate (a * in + b). + * @throws Exception + * @method Image linecache(array $options = []) Cache an image as a set of lines. + * @throws Exception + * @method static Image logmat(float $sigma, float $min_ampl, array $options = []) Make a Laplacian of Gaussian image. + * @throws Exception + * @method static Image magickload(string $filename, array $options = []) Load file with ImageMagick7. + * @throws Exception + * @method static Image magickload_buffer(string $buffer, array $options = []) Load buffer with ImageMagick7. + * @throws Exception + * @method static Image magickload_source(Source $source, array $options = []) Load source with ImageMagick7. + * @throws Exception + * @method void magicksave(string $filename, array $options = []) Save file with ImageMagick. + * @throws Exception + * @method string magicksave_buffer(array $options = []) Save image to magick buffer. + * @throws Exception + * @method Image mapim(Image $index, array $options = []) Resample with a map image. + * @throws Exception + * @method Image maplut(Image $lut, array $options = []) Map an image though a lut. + * @throws Exception + * @method static Image mask_butterworth(integer $width, integer $height, float $order, float $frequency_cutoff, float $amplitude_cutoff, array $options = []) Make a butterworth filter. + * @throws Exception + * @method static Image mask_butterworth_band(integer $width, integer $height, float $order, float $frequency_cutoff_x, float $frequency_cutoff_y, float $radius, float $amplitude_cutoff, array $options = []) Make a butterworth_band filter. + * @throws Exception + * @method static Image mask_butterworth_ring(integer $width, integer $height, float $order, float $frequency_cutoff, float $amplitude_cutoff, float $ringwidth, array $options = []) Make a butterworth ring filter. + * @throws Exception + * @method static Image mask_fractal(integer $width, integer $height, float $fractal_dimension, array $options = []) Make fractal filter. + * @throws Exception + * @method static Image mask_gaussian(integer $width, integer $height, float $frequency_cutoff, float $amplitude_cutoff, array $options = []) Make a gaussian filter. + * @throws Exception + * @method static Image mask_gaussian_band(integer $width, integer $height, float $frequency_cutoff_x, float $frequency_cutoff_y, float $radius, float $amplitude_cutoff, array $options = []) Make a gaussian filter. + * @throws Exception + * @method static Image mask_gaussian_ring(integer $width, integer $height, float $frequency_cutoff, float $amplitude_cutoff, float $ringwidth, array $options = []) Make a gaussian ring filter. + * @throws Exception + * @method static Image mask_ideal(integer $width, integer $height, float $frequency_cutoff, array $options = []) Make an ideal filter. + * @throws Exception + * @method static Image mask_ideal_band(integer $width, integer $height, float $frequency_cutoff_x, float $frequency_cutoff_y, float $radius, array $options = []) Make an ideal band filter. + * @throws Exception + * @method static Image mask_ideal_ring(integer $width, integer $height, float $frequency_cutoff, float $ringwidth, array $options = []) Make an ideal ring filter. + * @throws Exception + * @method Image match(Image $sec, integer $xr1, integer $yr1, integer $xs1, integer $ys1, integer $xr2, integer $yr2, integer $xs2, integer $ys2, array $options = []) First-order match of two images. + * @throws Exception + * @method Image math(string $math, array $options = []) Apply a math operation to an image. + * @see OperationMath for possible values for $math + * @throws Exception + * @method Image math2(Image $right, string $math2, array $options = []) Binary math operations. + * @see OperationMath2 for possible values for $math2 + * @throws Exception + * @method Image math2_const(string $math2, float[]|float $c, array $options = []) Binary math operations with a constant. + * @see OperationMath2 for possible values for $math2 + * @throws Exception + * @method static Image matload(string $filename, array $options = []) Load mat from file. + * @throws Exception + * @method Image matrixinvert(array $options = []) Invert a matrix. + * @throws Exception + * @method static Image matrixload(string $filename, array $options = []) Load matrix. + * @throws Exception + * @method static Image matrixload_source(Source $source, array $options = []) Load matrix. + * @throws Exception + * @method Image matrixmultiply(Image $right, array $options = []) Multiply two matrices. + * @throws Exception + * @method void matrixprint(array $options = []) Print matrix. + * @throws Exception + * @method void matrixsave(string $filename, array $options = []) Save image to matrix. + * @throws Exception + * @method void matrixsave_target(Target $target, array $options = []) Save image to matrix. + * @throws Exception + * @method float max(array $options = []) Find image maximum. + * @throws Exception + * @method Image maxpair(Image $right, array $options = []) Maximum of a pair of images. + * @throws Exception + * @method Image measure(integer $h, integer $v, array $options = []) Measure a set of patches on a color chart. + * @throws Exception + * @method Image merge(Image $sec, string $direction, integer $dx, integer $dy, array $options = []) Merge two images. + * @see Direction for possible values for $direction + * @throws Exception + * @method float min(array $options = []) Find image minimum. + * @throws Exception + * @method Image minpair(Image $right, array $options = []) Minimum of a pair of images. + * @throws Exception + * @method Image morph(Image $mask, string $morph, array $options = []) Morphology operation. + * @see OperationMorphology for possible values for $morph + * @throws Exception + * @method Image mosaic(Image $sec, string $direction, integer $xref, integer $yref, integer $xsec, integer $ysec, array $options = []) Mosaic two images. + * @see Direction for possible values for $direction + * @throws Exception + * @method Image mosaic1(Image $sec, string $direction, integer $xr1, integer $yr1, integer $xs1, integer $ys1, integer $xr2, integer $yr2, integer $xs2, integer $ys2, array $options = []) First-order mosaic of two images. + * @see Direction for possible values for $direction + * @throws Exception + * @method Image msb(array $options = []) Pick most-significant byte from an image. + * @throws Exception + * @method static Image niftiload(string $filename, array $options = []) Load NIfTI volume. + * @throws Exception + * @method static Image niftiload_source(Source $source, array $options = []) Load NIfTI volumes. + * @throws Exception + * @method void niftisave(string $filename, array $options = []) Save image to nifti file. + * @throws Exception + * @method static Image openexrload(string $filename, array $options = []) Load an OpenEXR image. + * @throws Exception + * @method static Image openslideload(string $filename, array $options = []) Load file with OpenSlide. + * @throws Exception + * @method static Image openslideload_source(Source $source, array $options = []) Load source with OpenSlide. + * @throws Exception + * @method static Image pdfload(string $filename, array $options = []) Load PDF from file (poppler). + * @throws Exception + * @method static Image pdfload_buffer(string $buffer, array $options = []) Load PDF from buffer (poppler). + * @throws Exception + * @method static Image pdfload_source(Source $source, array $options = []) Load PDF from source (poppler). + * @throws Exception + * @method integer percent(float $percent, array $options = []) Find threshold for percent of pixels. + * @throws Exception + * @method static Image perlin(integer $width, integer $height, array $options = []) Make a perlin noise image. + * @throws Exception + * @method Image phasecor(Image $in2, array $options = []) Calculate phase correlation. + * @throws Exception + * @method static Image pngload(string $filename, array $options = []) Load png from file. + * @throws Exception + * @method static Image pngload_buffer(string $buffer, array $options = []) Load png from buffer. + * @throws Exception + * @method static Image pngload_source(Source $source, array $options = []) Load png from source. + * @throws Exception + * @method void pngsave(string $filename, array $options = []) Save image to file as png. + * @throws Exception + * @method string pngsave_buffer(array $options = []) Save image to buffer as png. + * @throws Exception + * @method void pngsave_target(Target $target, array $options = []) Save image to target as PNG. + * @throws Exception + * @method static Image ppmload(string $filename, array $options = []) Load ppm from file. + * @throws Exception + * @method static Image ppmload_buffer(string $buffer, array $options = []) Load ppm from buffer. + * @throws Exception + * @method static Image ppmload_source(Source $source, array $options = []) Load ppm from source. + * @throws Exception + * @method void ppmsave(string $filename, array $options = []) Save image to ppm file. + * @throws Exception + * @method void ppmsave_target(Target $target, array $options = []) Save to ppm. + * @throws Exception + * @method Image premultiply(array $options = []) Premultiply image alpha. + * @throws Exception + * @method Image prewitt(array $options = []) Prewitt edge detector. + * @throws Exception + * @method array profile(array $options = []) Find image profiles. + * Return array with: [ + * 'columns' => @type Image First non-zero pixel in column + * 'rows' => @type Image First non-zero pixel in row + * ]; + * @throws Exception + * @method static string profile_load(string $name, array $options = []) Load named ICC profile. + * @throws Exception + * @method array project(array $options = []) Find image projections. + * Return array with: [ + * 'columns' => @type Image Sums of columns + * 'rows' => @type Image Sums of rows + * ]; + * @throws Exception + * @method Image quadratic(Image $coeff, array $options = []) Resample an image with a quadratic transform. + * @throws Exception + * @method Image rad2float(array $options = []) Unpack Radiance coding to float RGB. + * @throws Exception + * @method static Image radload(string $filename, array $options = []) Load a Radiance image from a file. + * @throws Exception + * @method static Image radload_buffer(string $buffer, array $options = []) Load rad from buffer. + * @throws Exception + * @method static Image radload_source(Source $source, array $options = []) Load rad from source. + * @throws Exception + * @method void radsave(string $filename, array $options = []) Save image to Radiance file. + * @throws Exception + * @method string radsave_buffer(array $options = []) Save image to Radiance buffer. + * @throws Exception + * @method void radsave_target(Target $target, array $options = []) Save image to Radiance target. + * @throws Exception + * @method Image rank(integer $width, integer $height, integer $index, array $options = []) Rank filter. + * @throws Exception + * @method static Image rawload(string $filename, integer $width, integer $height, integer $bands, array $options = []) Load raw data from a file. + * @throws Exception + * @method void rawsave(string $filename, array $options = []) Save image to raw file. + * @throws Exception + * @method string rawsave_buffer(array $options = []) Write raw image to buffer. + * @throws Exception + * @method void rawsave_target(Target $target, array $options = []) Write raw image to target. + * @throws Exception + * @method Image recomb(Image $m, array $options = []) Linear recombination with matrix. + * @throws Exception + * @method Image reduce(float $hshrink, float $vshrink, array $options = []) Reduce an image. + * @throws Exception + * @method Image reduceh(float $hshrink, array $options = []) Shrink an image horizontally. + * @throws Exception + * @method Image reducev(float $vshrink, array $options = []) Shrink an image vertically. + * @throws Exception + * @method Image relational(Image $right, string $relational, array $options = []) Relational operation on two images. + * @see OperationRelational for possible values for $relational + * @throws Exception + * @method Image relational_const(string $relational, float[]|float $c, array $options = []) Relational operations against a constant. + * @see OperationRelational for possible values for $relational + * @throws Exception + * @method Image remainder_const(float[]|float $c, array $options = []) Remainder after integer division of an image and a constant. + * @throws Exception + * @method Image remosaic(string $old_str, string $new_str, array $options = []) Rebuild an mosaiced image. + * @throws Exception + * @method Image replicate(integer $across, integer $down, array $options = []) Replicate an image. + * @throws Exception + * @method Image resize(float $scale, array $options = []) Resize an image. + * @throws Exception + * @method Image rot(string $angle, array $options = []) Rotate an image. + * @see Angle for possible values for $angle + * @throws Exception + * @method Image rot45(array $options = []) Rotate an image. + * @throws Exception + * @method Image rotate(float $angle, array $options = []) Rotate an image by a number of degrees. + * @throws Exception + * @method Image round(string $round, array $options = []) Perform a round function on an image. + * @see OperationRound for possible values for $round + * @throws Exception + * @method Image sRGB2HSV(array $options = []) Transform sRGB to HSV. + * @throws Exception + * @method Image sRGB2scRGB(array $options = []) Convert an sRGB image to scRGB. + * @throws Exception + * @method Image scRGB2BW(array $options = []) Convert scRGB to BW. + * @throws Exception + * @method Image scRGB2XYZ(array $options = []) Transform scRGB to XYZ. + * @throws Exception + * @method Image scRGB2sRGB(array $options = []) Convert scRGB to sRGB. + * @throws Exception + * @method Image scale(array $options = []) Scale an image to uchar. + * @throws Exception + * @method Image scharr(array $options = []) Scharr edge detector. + * @throws Exception + * @method static Image sdf(integer $width, integer $height, string $shape, array $options = []) Create an SDF image. + * @see SdfShape for possible values for $shape + * @throws Exception + * @method Image sequential(array $options = []) Check sequential access. + * @throws Exception + * @method Image sharpen(array $options = []) Unsharp masking for print. + * @throws Exception + * @method Image shrink(float $hshrink, float $vshrink, array $options = []) Shrink an image. + * @throws Exception + * @method Image shrinkh(integer $hshrink, array $options = []) Shrink an image horizontally. + * @throws Exception + * @method Image shrinkv(integer $vshrink, array $options = []) Shrink an image vertically. + * @throws Exception + * @method Image sign(array $options = []) Unit vector of pixel. + * @throws Exception + * @method Image similarity(array $options = []) Similarity transform of an image. + * @throws Exception + * @method static Image sines(integer $width, integer $height, array $options = []) Make a 2D sine wave. + * @throws Exception + * @method Image smartcrop(integer $width, integer $height, array $options = []) Extract an area from an image. + * @throws Exception + * @method Image sobel(array $options = []) Sobel edge detector. + * @throws Exception + * @method Image spcor(Image $ref, array $options = []) Spatial correlation. + * @throws Exception + * @method Image spectrum(array $options = []) Make displayable power spectrum. + * @throws Exception + * @method Image stats(array $options = []) Find many image stats. + * @throws Exception + * @method Image stdif(integer $width, integer $height, array $options = []) Statistical difference. + * @throws Exception + * @method Image subsample(integer $xfac, integer $yfac, array $options = []) Subsample an image. + * @throws Exception + * @method static Image sum(Image[]|Image $in, array $options = []) Sum an array of images. + * @throws Exception + * @method static Image svgload(string $filename, array $options = []) Load SVG with rsvg. + * @throws Exception + * @method static Image svgload_buffer(string $buffer, array $options = []) Load SVG with rsvg. + * @throws Exception + * @method static Image svgload_source(Source $source, array $options = []) Load svg from source. + * @throws Exception + * @method static Image switch(Image[]|Image $tests, array $options = []) Find the index of the first non-zero pixel in tests. + * @throws Exception + * @method static void system(string $cmd_format, array $options = []) Run an external command. + * @throws Exception + * @method static Image text(string $text, array $options = []) Make a text image. + * @throws Exception + * @method static Image thumbnail(string $filename, integer $width, array $options = []) Generate thumbnail from file. + * @throws Exception + * @method static Image thumbnail_buffer(string $buffer, integer $width, array $options = []) Generate thumbnail from buffer. + * @throws Exception + * @method Image thumbnail_image(integer $width, array $options = []) Generate thumbnail from image. + * @throws Exception + * @method static Image thumbnail_source(Source $source, integer $width, array $options = []) Generate thumbnail from source. + * @throws Exception + * @method static Image tiffload(string $filename, array $options = []) Load tiff from file. + * @throws Exception + * @method static Image tiffload_buffer(string $buffer, array $options = []) Load tiff from buffer. + * @throws Exception + * @method static Image tiffload_source(Source $source, array $options = []) Load tiff from source. + * @throws Exception + * @method void tiffsave(string $filename, array $options = []) Save image to tiff file. + * @throws Exception + * @method string tiffsave_buffer(array $options = []) Save image to tiff buffer. + * @throws Exception + * @method void tiffsave_target(Target $target, array $options = []) Save image to tiff target. + * @throws Exception + * @method Image tilecache(array $options = []) Cache an image as a set of tiles. + * @throws Exception + * @method static Image tonelut(array $options = []) Build a look-up table. + * @throws Exception + * @method Image transpose3d(array $options = []) Transpose3d an image. + * @throws Exception + * @method Image uhdr2scRGB(array $options = []) Transform uhdr to scRGB. + * @throws Exception + * @method static Image uhdrload(string $filename, array $options = []) Load a UHDR image. + * @throws Exception + * @method static Image uhdrload_buffer(string $buffer, array $options = []) Load a UHDR image. + * @throws Exception + * @method static Image uhdrload_source(Source $source, array $options = []) Load a UHDR image. + * @throws Exception + * @method void uhdrsave(string $filename, array $options = []) Save image in UltraHDR format. + * @throws Exception + * @method string uhdrsave_buffer(array $options = []) Save image in UltraHDR format. + * @throws Exception + * @method void uhdrsave_target(Target $target, array $options = []) Save image in UltraHDR format. + * @throws Exception + * @method Image unpremultiply(array $options = []) Unpremultiply image alpha. + * @throws Exception + * @method static Image vipsload(string $filename, array $options = []) Load vips from file. + * @throws Exception + * @method static Image vipsload_source(Source $source, array $options = []) Load vips from source. + * @throws Exception + * @method void vipssave(string $filename, array $options = []) Save image to file in vips format. + * @throws Exception + * @method void vipssave_target(Target $target, array $options = []) Save image to target in vips format. + * @throws Exception + * @method static Image webpload(string $filename, array $options = []) Load webp from file. + * @throws Exception + * @method static Image webpload_buffer(string $buffer, array $options = []) Load webp from buffer. + * @throws Exception + * @method static Image webpload_source(Source $source, array $options = []) Load webp from source. + * @throws Exception + * @method void webpsave(string $filename, array $options = []) Save as WebP. + * @throws Exception + * @method string webpsave_buffer(array $options = []) Save as WebP. + * @throws Exception + * @method void webpsave_mime(array $options = []) Save image to webp mime. + * @throws Exception + * @method void webpsave_target(Target $target, array $options = []) Save as WebP. + * @throws Exception + * @method static Image worley(integer $width, integer $height, array $options = []) Make a worley noise image. + * @throws Exception + * @method Image wrap(array $options = []) Wrap image origin. + * @throws Exception + * @method static Image xyz(integer $width, integer $height, array $options = []) Make an image where pixel values are coordinates. + * @throws Exception + * @method static Image zone(integer $width, integer $height, array $options = []) Make a zone plate. + * @throws Exception + * @method Image zoom(integer $xfac, integer $yfac, array $options = []) Zoom an image. + * @throws Exception + * + * @property integer $width Image width in pixels + * @property integer $height Image height in pixels + * @property integer $bands Number of bands in image + * @property string $format Pixel format in image + * @see BandFormat for possible values + * @property string $coding Pixel coding + * @see Coding for possible values + * @property string $interpretation Pixel interpretation + * @see Interpretation for possible values + * @property integer $xoffset Horizontal offset of origin + * @property integer $yoffset Vertical offset of origin + * @property float $xres Horizontal resolution in pixels/mm + * @property float $yres Vertical resolution in pixels/mm + * @property string $filename Image filename + */ +abstract class ImageAutodoc extends \Jcupitt\Vips\VipsObject +{ + abstract public function __set(string $name, $value); + abstract public function __get(string $name); +} diff --git a/src/wp-includes/php-vips/src/Intent.php b/src/wp-includes/php-vips/src/Intent.php new file mode 100644 index 0000000000000..df365969a2b53 --- /dev/null +++ b/src/wp-includes/php-vips/src/Intent.php @@ -0,0 +1,56 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * The Intent enum. + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +abstract class Intent +{ + const PERCEPTUAL = 'perceptual'; + const RELATIVE = 'relative'; + const SATURATION = 'saturation'; + const ABSOLUTE = 'absolute'; + const AUTO = 'auto'; +} diff --git a/src/wp-includes/php-vips/src/Interesting.php b/src/wp-includes/php-vips/src/Interesting.php new file mode 100644 index 0000000000000..efd142df75b04 --- /dev/null +++ b/src/wp-includes/php-vips/src/Interesting.php @@ -0,0 +1,58 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * The Interesting enum. + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +abstract class Interesting +{ + const NONE = 'none'; + const CENTRE = 'centre'; + const ENTROPY = 'entropy'; + const ATTENTION = 'attention'; + const LOW = 'low'; + const HIGH = 'high'; + const ALL = 'all'; +} diff --git a/src/wp-includes/php-vips/src/Interpolate.php b/src/wp-includes/php-vips/src/Interpolate.php new file mode 100644 index 0000000000000..ca76ec834b448 --- /dev/null +++ b/src/wp-includes/php-vips/src/Interpolate.php @@ -0,0 +1,98 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/libvips/php-vips + */ +namespace Jcupitt\Vips; + +/** + * This class holds a pointer to a VipsInterpolate (the libvips + * base class for interpolators) and manages argument introspection and + * operation call. + * + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/libvips/php-vips + */ +class Interpolate extends \Jcupitt\Vips\VipsObject +{ + /** + * A pointer to the underlying Interpolate. This is the same as the + * GObject, just cast to Interpolate to help FFI. + * + * @internal + */ + public \FFI\CData $pointer; + public function __construct(\FFI\CData $pointer) + { + $this->pointer = \Jcupitt\Vips\FFI::vips()->cast(\Jcupitt\Vips\FFI::ctypes("VipsInterpolate"), $pointer); + parent::__construct($pointer); + } + /** + * Make an interpolator from a name. + * + * @param string $name Name of the interpolator. + * + * Possible interpolators are: + * - `'nearest'`: Use nearest neighbour interpolation. + * - `'bicubic'`: Use bicubic interpolation. + * - `'bilinear'`: Use bilinear interpolation (the default). + * - `'nohalo'`: Use Nohalo interpolation. + * - `'lbb'`: Use LBB interpolation. + * - `'vsqbs'`: Use the VSQBS interpolation. + * + * @return Interpolate The interpolator. + * @throws Exception If unable to make a new interpolator from $name. + */ + public static function newFromName(string $name): \Jcupitt\Vips\Interpolate + { + $pointer = \Jcupitt\Vips\FFI::vips()->vips_interpolate_new($name); + if ($pointer == null) { + throw new \Jcupitt\Vips\Exception(); + } + return new \Jcupitt\Vips\Interpolate($pointer); + } +} +/* + * Local variables: + * tab-width: 4 + * c-basic-offset: 4 + * End: + * vim600: expandtab sw=4 ts=4 fdm=marker + * vim<600: expandtab sw=4 ts=4 + */ diff --git a/src/wp-includes/php-vips/src/Interpretation.php b/src/wp-includes/php-vips/src/Interpretation.php new file mode 100644 index 0000000000000..19f4c3b39bcea --- /dev/null +++ b/src/wp-includes/php-vips/src/Interpretation.php @@ -0,0 +1,73 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * The Interpretation enum. + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +abstract class Interpretation +{ + const ERROR = 'error'; + const MULTIBAND = 'multiband'; + const B_W = 'b-w'; + const HISTOGRAM = 'histogram'; + const XYZ = 'xyz'; + const LAB = 'lab'; + const CMYK = 'cmyk'; + const LABQ = 'labq'; + const RGB = 'rgb'; + const CMC = 'cmc'; + const LCH = 'lch'; + const LABS = 'labs'; + const SRGB = 'srgb'; + const YXY = 'yxy'; + const FOURIER = 'fourier'; + const RGB16 = 'rgb16'; + const GREY16 = 'grey16'; + const MATRIX = 'matrix'; + const SCRGB = 'scrgb'; + const HSV = 'hsv'; + const OKLAB = 'oklab'; + const OKLCH = 'oklch'; +} diff --git a/src/wp-includes/php-vips/src/Introspect.php b/src/wp-includes/php-vips/src/Introspect.php new file mode 100644 index 0000000000000..9af86b24a7069 --- /dev/null +++ b/src/wp-includes/php-vips/src/Introspect.php @@ -0,0 +1,202 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/libvips/php-vips + */ +namespace Jcupitt\Vips; + +/** + * Introspect a VipsOperation and discover everything we can. This is called + * on demand once per operation and the results held in a cache. + * + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/libvips/php-vips + */ +class Introspect +{ + /** + * The operation nickname (eg. "add"). + */ + public string $name; + /** + * The operation description (e.g. "add two images"). + */ + public string $description; + /** + * The operation flags (e.g. SEQUENTIAL | DEPRECATED). + */ + public int $flags; + /** + * A hash from arg name to a hash of details. + */ + public array $arguments; + /** + * Arrays of arg names, in order and by category, eg. $this->required_input + * = ["filename"]. + */ + public array $required_input; + public array $optional_input; + public array $required_output; + public array $optional_output; + /** + * The name of the arg this operation uses as "this". + */ + public string $member_this; + /** + * And the required input args, without the "this". + */ + public array $method_args; + /** + * @throws Exception + */ + public function __construct($operation_name) + { + $this->name = $operation_name; + $operation = \Jcupitt\Vips\VipsOperation::newFromName($operation_name); + $this->description = $operation->getDescription(); + $p_names = \Jcupitt\Vips\FFI::vips()->new("char**[1]"); + $p_flags = \Jcupitt\Vips\FFI::vips()->new("int*[1]"); + $p_n_args = \Jcupitt\Vips\FFI::vips()->new("int[1]"); + $result = \Jcupitt\Vips\FFI::vips()->vips_object_get_args(\Jcupitt\Vips\FFI::vips()->cast(\Jcupitt\Vips\FFI::ctypes("VipsObject"), $operation->pointer), $p_names, $p_flags, $p_n_args); + if ($result != 0) { + throw new \Jcupitt\Vips\Exception(); + } + $p_names = $p_names[0]; + $p_flags = $p_flags[0]; + $n_args = $p_n_args[0]; + # make a hash from arg name to flags + $argumentFlags = []; + for ($i = 0; $i < $n_args; $i++) { + if (($p_flags[$i] & \Jcupitt\Vips\ArgumentFlags::CONSTRUCT) != 0) { + # make sure we're using "_" to separate arg components, though + # I think libvips is "_" everywhere now + $name = \FFI::string($p_names[$i]); + $name = str_replace("-", "_", $name); + $argumentFlags[$name] = $p_flags[$i]; + } + } + # make a hash from arg name to detailed arg info + $this->arguments = []; + foreach ($argumentFlags as $name => $flags) { + $this->arguments[$name] = ["name" => $name, "flags" => $flags, "blurb" => $operation->getBlurb($name), "type" => $operation->getType($name)]; + } + # split args into categories + $this->required_input = []; + $this->optional_input = []; + $this->required_output = []; + $this->optional_output = []; + foreach ($this->arguments as $name => $details) { + $flags = $details["flags"]; + if ($flags & \Jcupitt\Vips\ArgumentFlags::INPUT && $flags & \Jcupitt\Vips\ArgumentFlags::REQUIRED && !($flags & \Jcupitt\Vips\ArgumentFlags::DEPRECATED)) { + $this->required_input[] = $name; + # required inputs which we MODIFY are also required outputs + if ($flags & \Jcupitt\Vips\ArgumentFlags::MODIFY) { + $this->required_output[] = $name; + } + } + if ($flags & \Jcupitt\Vips\ArgumentFlags::OUTPUT && $flags & \Jcupitt\Vips\ArgumentFlags::REQUIRED && !($flags & \Jcupitt\Vips\ArgumentFlags::DEPRECATED)) { + $this->required_output[] = $name; + } + # we let deprecated optional args through, but warn about them + # if they get used, see below + if ($flags & \Jcupitt\Vips\ArgumentFlags::INPUT && !($flags & \Jcupitt\Vips\ArgumentFlags::REQUIRED)) { + $this->optional_input[] = $name; + } + if ($flags & \Jcupitt\Vips\ArgumentFlags::OUTPUT && !($flags & \Jcupitt\Vips\ArgumentFlags::REQUIRED)) { + $this->optional_output[] = $name; + } + } + # find the first required input image arg, if any ... that will be self + $this->member_this = ""; + foreach ($this->required_input as $name) { + $type = $this->arguments[$name]["type"]; + if ($type == \Jcupitt\Vips\FFI::gtypes("VipsImage")) { + $this->member_this = $name; + break; + } + } + # method args are required args, but without the image they are a + # method on + $this->method_args = $this->required_input; + if ($this->member_this != "") { + $index = array_search($this->member_this, $this->method_args); + array_splice($this->method_args, $index); + } + \Jcupitt\Vips\Utils::debugLog($operation_name, ['introspect' => strval($this)]); + } + public function __toString(): string + { + $result = "{$this->name}:\n"; + foreach ($this->arguments as $name => $details) { + $flags = $details["flags"]; + $blurb = $details["blurb"]; + $type = $details["type"]; + $typeName = \Jcupitt\Vips\FFI::gobject()->g_type_name($type); + $result .= " {$name}:\n"; + $result .= " flags: {$flags}\n"; + foreach (\Jcupitt\Vips\ArgumentFlags::NAMES as $flag_name => $flag) { + if ($flags & $flag) { + $result .= " {$flag_name}\n"; + } + } + $result .= " blurb: {$blurb}\n"; + $result .= " type: {$typeName}\n"; + } + $info = implode(", ", $this->required_input); + $result .= "required input: {$info}\n"; + $info = implode(", ", $this->required_output); + $result .= "required output: {$info}\n"; + $info = implode(", ", $this->optional_input); + $result .= "optional input: {$info}\n"; + $info = implode(", ", $this->optional_output); + $result .= "optional output: {$info}\n"; + $result .= "member_this: {$this->member_this}\n"; + $info = implode(", ", $this->method_args); + $result .= "method args: {$info}\n"; + return $result; + } +} +/* + * Local variables: + * tab-width: 4 + * c-basic-offset: 4 + * End: + * vim600: expandtab sw=4 ts=4 fdm=marker + * vim<600: expandtab sw=4 ts=4 + */ diff --git a/src/wp-includes/php-vips/src/Kernel.php b/src/wp-includes/php-vips/src/Kernel.php new file mode 100644 index 0000000000000..df0de6caf2672 --- /dev/null +++ b/src/wp-includes/php-vips/src/Kernel.php @@ -0,0 +1,59 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * The Kernel enum. + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +abstract class Kernel +{ + const NEAREST = 'nearest'; + const LINEAR = 'linear'; + const CUBIC = 'cubic'; + const MITCHELL = 'mitchell'; + const LANCZOS2 = 'lanczos2'; + const LANCZOS3 = 'lanczos3'; + const MKS2013 = 'mks2013'; + const MKS2021 = 'mks2021'; +} diff --git a/src/wp-includes/php-vips/src/OperationBoolean.php b/src/wp-includes/php-vips/src/OperationBoolean.php new file mode 100644 index 0000000000000..538b7f91b0272 --- /dev/null +++ b/src/wp-includes/php-vips/src/OperationBoolean.php @@ -0,0 +1,56 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * The OperationBoolean enum. + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +abstract class OperationBoolean +{ + const AND1 = 'and'; + const OR1 = 'or'; + const EOR = 'eor'; + const LSHIFT = 'lshift'; + const RSHIFT = 'rshift'; +} diff --git a/src/wp-includes/php-vips/src/OperationComplex.php b/src/wp-includes/php-vips/src/OperationComplex.php new file mode 100644 index 0000000000000..a5485f8e7d1ad --- /dev/null +++ b/src/wp-includes/php-vips/src/OperationComplex.php @@ -0,0 +1,54 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * The OperationComplex enum. + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +abstract class OperationComplex +{ + const POLAR = 'polar'; + const RECT = 'rect'; + const CONJ = 'conj'; +} diff --git a/src/wp-includes/php-vips/src/OperationComplex2.php b/src/wp-includes/php-vips/src/OperationComplex2.php new file mode 100644 index 0000000000000..3b11aea91c6e1 --- /dev/null +++ b/src/wp-includes/php-vips/src/OperationComplex2.php @@ -0,0 +1,52 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * The OperationComplex2 enum. + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +abstract class OperationComplex2 +{ + const CROSS_PHASE = 'cross-phase'; +} diff --git a/src/wp-includes/php-vips/src/OperationComplexget.php b/src/wp-includes/php-vips/src/OperationComplexget.php new file mode 100644 index 0000000000000..fc8c961801210 --- /dev/null +++ b/src/wp-includes/php-vips/src/OperationComplexget.php @@ -0,0 +1,53 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * The OperationComplexget enum. + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +abstract class OperationComplexget +{ + const REAL = 'real'; + const IMAG = 'imag'; +} diff --git a/src/wp-includes/php-vips/src/OperationMath.php b/src/wp-includes/php-vips/src/OperationMath.php new file mode 100644 index 0000000000000..71338f81dbfb2 --- /dev/null +++ b/src/wp-includes/php-vips/src/OperationMath.php @@ -0,0 +1,67 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * The OperationMath enum. + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +abstract class OperationMath +{ + const SIN = 'sin'; + const COS = 'cos'; + const TAN = 'tan'; + const ASIN = 'asin'; + const ACOS = 'acos'; + const ATAN = 'atan'; + const LOG = 'log'; + const LOG10 = 'log10'; + const EXP = 'exp'; + const EXP10 = 'exp10'; + const SINH = 'sinh'; + const COSH = 'cosh'; + const TANH = 'tanh'; + const ASINH = 'asinh'; + const ACOSH = 'acosh'; + const ATANH = 'atanh'; +} diff --git a/src/wp-includes/php-vips/src/OperationMath2.php b/src/wp-includes/php-vips/src/OperationMath2.php new file mode 100644 index 0000000000000..7dfafc37b296b --- /dev/null +++ b/src/wp-includes/php-vips/src/OperationMath2.php @@ -0,0 +1,54 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * The OperationMath2 enum. + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +abstract class OperationMath2 +{ + const POW = 'pow'; + const WOP = 'wop'; + const ATAN2 = 'atan2'; +} diff --git a/src/wp-includes/php-vips/src/OperationMorphology.php b/src/wp-includes/php-vips/src/OperationMorphology.php new file mode 100644 index 0000000000000..fc80aaca0b49a --- /dev/null +++ b/src/wp-includes/php-vips/src/OperationMorphology.php @@ -0,0 +1,53 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * The OperationMorphology enum. + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +abstract class OperationMorphology +{ + const ERODE = 'erode'; + const DILATE = 'dilate'; +} diff --git a/src/wp-includes/php-vips/src/OperationRelational.php b/src/wp-includes/php-vips/src/OperationRelational.php new file mode 100644 index 0000000000000..510ecddf22c6e --- /dev/null +++ b/src/wp-includes/php-vips/src/OperationRelational.php @@ -0,0 +1,57 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * The OperationRelational enum. + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +abstract class OperationRelational +{ + const EQUAL = 'equal'; + const NOTEQ = 'noteq'; + const LESS = 'less'; + const LESSEQ = 'lesseq'; + const MORE = 'more'; + const MOREEQ = 'moreeq'; +} diff --git a/src/wp-includes/php-vips/src/OperationRound.php b/src/wp-includes/php-vips/src/OperationRound.php new file mode 100644 index 0000000000000..3407e8bc0d9cd --- /dev/null +++ b/src/wp-includes/php-vips/src/OperationRound.php @@ -0,0 +1,54 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * The OperationRound enum. + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +abstract class OperationRound +{ + const RINT = 'rint'; + const CEIL = 'ceil'; + const FLOOR = 'floor'; +} diff --git a/src/wp-includes/php-vips/src/PCS.php b/src/wp-includes/php-vips/src/PCS.php new file mode 100644 index 0000000000000..92ec7c6650caf --- /dev/null +++ b/src/wp-includes/php-vips/src/PCS.php @@ -0,0 +1,53 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * The PCS enum. + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +abstract class PCS +{ + const LAB = 'lab'; + const XYZ = 'xyz'; +} diff --git a/src/wp-includes/php-vips/src/Precision.php b/src/wp-includes/php-vips/src/Precision.php new file mode 100644 index 0000000000000..9bfbc5a78e4ae --- /dev/null +++ b/src/wp-includes/php-vips/src/Precision.php @@ -0,0 +1,54 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * The Precision enum. + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +abstract class Precision +{ + const INTEGER = 'integer'; + const FLOAT = 'float'; + const APPROXIMATE = 'approximate'; +} diff --git a/src/wp-includes/php-vips/src/RegionShrink.php b/src/wp-includes/php-vips/src/RegionShrink.php new file mode 100644 index 0000000000000..fe2092cfb5f9f --- /dev/null +++ b/src/wp-includes/php-vips/src/RegionShrink.php @@ -0,0 +1,57 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * The RegionShrink enum. + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +abstract class RegionShrink +{ + const MEAN = 'mean'; + const MEDIAN = 'median'; + const MODE = 'mode'; + const MAX = 'max'; + const MIN = 'min'; + const NEAREST = 'nearest'; +} diff --git a/src/wp-includes/php-vips/src/SdfShape.php b/src/wp-includes/php-vips/src/SdfShape.php new file mode 100644 index 0000000000000..b79b7def93e21 --- /dev/null +++ b/src/wp-includes/php-vips/src/SdfShape.php @@ -0,0 +1,55 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * The SdfShape enum. + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +abstract class SdfShape +{ + const CIRCLE = 'circle'; + const BOX = 'box'; + const ROUNDED_BOX = 'rounded-box'; + const LINE = 'line'; +} diff --git a/src/wp-includes/php-vips/src/Size.php b/src/wp-includes/php-vips/src/Size.php new file mode 100644 index 0000000000000..1c18791f5d638 --- /dev/null +++ b/src/wp-includes/php-vips/src/Size.php @@ -0,0 +1,55 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * The Size enum. + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +abstract class Size +{ + const BOTH = 'both'; + const UP = 'up'; + const DOWN = 'down'; + const FORCE = 'force'; +} diff --git a/src/wp-includes/php-vips/src/Source.php b/src/wp-includes/php-vips/src/Source.php new file mode 100644 index 0000000000000..2c79c75ef8aad --- /dev/null +++ b/src/wp-includes/php-vips/src/Source.php @@ -0,0 +1,81 @@ +pointer = \Jcupitt\Vips\FFI::vips()->cast(\Jcupitt\Vips\FFI::ctypes('VipsSource'), $pointer); + parent::__construct($pointer); + } + /** + * Make a new source from a file descriptor. For example: + * + * ```php + * $source = Source::newFromDescriptor(0); + * ``` + * + * Makes a descriptor attached to stdin. + * You can pass this source to (for example) @see Image::newFromSource() + * @throws Exception + */ + public static function newFromDescriptor(int $descriptor): self + { + $pointer = \Jcupitt\Vips\FFI::vips()->vips_source_new_from_descriptor($descriptor); + if ($pointer === null) { + throw new \Jcupitt\Vips\Exception("can't create source from descriptor {$descriptor}"); + } + return new self($pointer); + } + /** + * Make a new source from a filename. For example: + * + * ```php + * $source = Source::newFromFile("myfile.jpg"); + * ``` + * + * You can pass this source to (for example) @see Image::newFromSource() + * @throws Exception + */ + public static function newFromFile(string $filename): self + { + $pointer = \Jcupitt\Vips\FFI::vips()->vips_source_new_from_file($filename); + if ($pointer === null) { + throw new \Jcupitt\Vips\Exception("can't create source from filename {$filename}"); + } + return new self($pointer); + } + /** + * Make a new source from a memory buffer. For example: + * + * ```php + * $source = Source::newFromMemory(file_get_contents("myfile.jpg")); + * ``` + * + * You can pass this source to (for example) @see Image::newFromSource() + * @throws Exception + */ + public static function newFromMemory(string $data): self + { + $blob = \Jcupitt\Vips\FFI::vips()->vips_blob_copy($data, strlen($data)); + if ($blob === null) { + throw new \Jcupitt\Vips\Exception("can't create source from memory"); + } + $pointer = \Jcupitt\Vips\FFI::vips()->vips_source_new_from_blob($blob); + if ($pointer === null) { + \Jcupitt\Vips\FFI::vips()->vips_area_unref($blob); + throw new \Jcupitt\Vips\Exception("can't create source from memory"); + } + $source = new self($pointer); + \Jcupitt\Vips\FFI::vips()->vips_area_unref($blob); + return $source; + } +} diff --git a/src/wp-includes/php-vips/src/SourceCustom.php b/src/wp-includes/php-vips/src/SourceCustom.php new file mode 100644 index 0000000000000..6dca955427a94 --- /dev/null +++ b/src/wp-includes/php-vips/src/SourceCustom.php @@ -0,0 +1,50 @@ +pointer = \Jcupitt\Vips\FFI::vips()->vips_source_custom_new(); + parent::__construct($this->pointer); + } + /** + * Attach a read handler. + * + * The interface is similar to fread. The handler is given a number + * of bytes to fetch, and should return a bytes-like object containing up + * to that number of bytes. If there is no more data available, it should + * return null. + */ + public function onRead(callable $callback): void + { + $this->signalConnect('read', $callback); + } + /** + * Attach a seek handler. + * + * The interface is the same as fseek, so the handler is passed + * parameters for $offset and $whence with the same meanings. + * However, the handler MUST return the new seek position. A simple way + * to do this is to call ftell() and return that result. + * Seek handlers are optional. If you do not set one, your source will be + * treated as unseekable and libvips will do extra caching. + * + * $whence in particular: + * - 0 => start + * - 1 => current position + * - 2 => end + */ + public function onSeek(callable $callback): void + { + $this->signalConnect('seek', $callback); + } +} diff --git a/src/wp-includes/php-vips/src/SourceResource.php b/src/wp-includes/php-vips/src/SourceResource.php new file mode 100644 index 0000000000000..0624b94687ccf --- /dev/null +++ b/src/wp-includes/php-vips/src/SourceResource.php @@ -0,0 +1,36 @@ +resource = $resource; + parent::__construct(); + $this->onRead(static function (int $length) use (&$resource): ?string { + return fread($resource, $length) ?: null; + }); + if (stream_get_meta_data($resource)['seekable']) { + $this->onSeek(static function (int $offset, int $whence) use (&$resource): int { + fseek($resource, $offset, $whence); + return ftell($resource); + }); + } + } + public function __destruct() + { + fclose($this->resource); + parent::__destruct(); + } +} diff --git a/src/wp-includes/php-vips/src/Target.php b/src/wp-includes/php-vips/src/Target.php new file mode 100644 index 0000000000000..c1eeadebd535b --- /dev/null +++ b/src/wp-includes/php-vips/src/Target.php @@ -0,0 +1,74 @@ +pointer = \Jcupitt\Vips\FFI::vips()->cast(\Jcupitt\Vips\FFI::ctypes('VipsTarget'), $pointer); + parent::__construct($pointer); + } + /** + * Make a new target to write to a file descriptor. For example: + * + * ```php + * $target = Target::newToDescriptor(1); + * ``` + * + * Makes a descriptor attached to stdout. + * You can pass this target to (for example) @see Image::writeToTarget() + * @throws Exception + */ + public static function newToDescriptor(int $descriptor): self + { + $pointer = \Jcupitt\Vips\FFI::vips()->vips_target_new_to_descriptor($descriptor); + if ($pointer === null) { + throw new \Jcupitt\Vips\Exception("can't create output target from descriptor {$descriptor}"); + } + return new self($pointer); + } + /** + * Make a new target to write to a filename. For example: + * + * ```php + * $target = Target::newToFile("myfile.jpg"); + * ``` + * + * You can pass this target to (for example) @see Image::writeToTarget() + * @throws Exception + */ + public static function newToFile(string $filename): self + { + $pointer = \Jcupitt\Vips\FFI::vips()->vips_target_new_to_file($filename); + if ($pointer === null) { + throw new \Jcupitt\Vips\Exception("can't create output target from filename {$filename}"); + } + return new self($pointer); + } + /** + * Make a new target to write to a memory buffer. For example: + * + * ```php + * $target = Target::newToMemory(); + * ``` + * + * You can pass this target to (for example) @see Image::writeToTarget() + * @throws Exception + */ + public static function newToMemory(): self + { + $pointer = \Jcupitt\Vips\FFI::vips()->vips_target_new_to_memory(); + if ($pointer === null) { + throw new \Jcupitt\Vips\Exception("can't create output target from memory"); + } + return new self($pointer); + } +} diff --git a/src/wp-includes/php-vips/src/TargetCustom.php b/src/wp-includes/php-vips/src/TargetCustom.php new file mode 100644 index 0000000000000..0adbd78fa29af --- /dev/null +++ b/src/wp-includes/php-vips/src/TargetCustom.php @@ -0,0 +1,105 @@ +pointer = \Jcupitt\Vips\FFI::vips()->vips_target_custom_new(); + parent::__construct($this->pointer); + } + /** + * Attach a write handler. + * + * The interface is similar to fwrite(). The handler is given a + * bytes-like object to write, and should return the number of bytes + * written. + * + * Unlike fwrite, you should return -1 on error. + * + * @throws Exception + */ + public function onWrite(callable $callback): void + { + $this->signalConnect('write', $callback); + } + /** + * Attach a read handler. + * + * The interface is similar to fread(). The handler is given a number + * of bytes to fetch, and should return a bytes-like object containing up + * to that number of bytes. If there is no more data available, it should + * return null. + * + * Read handlers on VipsTarget are optional. If you do not set one, your + * target will be treated as unreadable and libvips will be unable to + * write some file types (just TIFF, as of the time of writing). + */ + public function onRead(callable $callback): void + { + if (\Jcupitt\Vips\FFI::atLeast(8, 13)) { + $this->signalConnect('read', $callback); + } + } + /** + * Attach a seek handler. + * + * The interface is similar to fseek, so the handler is passed + * parameters for $offset and $whence with the same meanings. + * However, the handler MUST return the new seek position. A simple way + * to do this is to call ftell() and return that result. + * + * Seek handlers are optional. If you do not set one, your source will be + * treated as unseekable and libvips will do extra caching. + * + * $whence in particular: + * - 0 => start + * - 1 => current position + * - 2 => end + */ + public function onSeek(callable $callback): void + { + if (\Jcupitt\Vips\FFI::atLeast(8, 13)) { + $this->signalConnect('seek', $callback); + } + } + /** + * Attach an end handler. + * + * This optional handler is called at the end of write. It should do any + * cleaning up necessary, and return 0 on success and -1 on error. + * + * Automatically falls back to onFinish if libvips <8.13. + * + * @throws Exception + */ + public function onEnd(callable $callback): void + { + if (\Jcupitt\Vips\FFI::atLeast(8, 13)) { + $this->signalConnect('end', $callback); + } else { + $this->onFinish($callback); + } + } + /** + * Attach a finish handler. + * + * For libvips 8.13 and later, this method is deprecated in favour of + * onEnd(). + * + * @see TargetCustom::onEnd() + * @throws Exception + */ + public function onFinish(callable $callback): void + { + $this->signalConnect('finish', $callback); + } +} diff --git a/src/wp-includes/php-vips/src/TargetResource.php b/src/wp-includes/php-vips/src/TargetResource.php new file mode 100644 index 0000000000000..fdd64cc96a9d4 --- /dev/null +++ b/src/wp-includes/php-vips/src/TargetResource.php @@ -0,0 +1,48 @@ +resource = $resource; + parent::__construct(); + $this->onWrite(static function (string $buffer) use (&$resource): int { + return fwrite($resource, $buffer) ?: 0; + }); + $this->onEnd(static function () use (&$resource): void { + fclose($resource); + }); + $meta = stream_get_meta_data($resource); + // See: https://www.php.net/manual/en/function.fopen.php + if (substr($meta['mode'], -1) === '+') { + $this->onRead(static function (int $length) use (&$resource): ?string { + return fread($resource, $length) ?: null; + }); + } + if ($meta['seekable']) { + $this->onSeek(static function (int $offset, int $whence) use (&$resource): int { + fseek($resource, $offset, $whence); + return ftell($resource); + }); + } + } + public function __destruct() + { + if (is_resource($this->resource)) { + fclose($this->resource); + } + parent::__destruct(); + } +} diff --git a/src/wp-includes/php-vips/src/TextWrap.php b/src/wp-includes/php-vips/src/TextWrap.php new file mode 100644 index 0000000000000..0cbf7e2f8b5c3 --- /dev/null +++ b/src/wp-includes/php-vips/src/TextWrap.php @@ -0,0 +1,55 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * The TextWrap enum. + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +abstract class TextWrap +{ + const WORD = 'word'; + const CHAR = 'char'; + const WORD_CHAR = 'word-char'; + const NONE = 'none'; +} diff --git a/src/wp-includes/php-vips/src/Utils.php b/src/wp-includes/php-vips/src/Utils.php new file mode 100644 index 0000000000000..4d982be68db13 --- /dev/null +++ b/src/wp-includes/php-vips/src/Utils.php @@ -0,0 +1,116 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +namespace Jcupitt\Vips; + +/** + * Various utilities. + * + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/jcupitt/php-vips + */ +class Utils +{ + /** + * Log a debug message. + * + * @param string $name The method creating the messages. + * @param array $arguments The method arguments. + * + * @return void + */ + public static function debugLog(string $name, array $arguments): void + { + $logger = \Jcupitt\Vips\Config::getLogger(); + if ($logger) { + $logger->debug($name, $arguments); + } + } + /** + * Log an error message. + * + * @param string $message The error message. + * @param \Exception|null $exception The exception, if any. + * + * @return void + */ + public static function errorLog(string $message, ?\Exception $exception = null): void + { + $logger = \Jcupitt\Vips\Config::getLogger(); + if ($logger) { + $logger->error($message, $exception == null ? [] : ['exception' => $exception]); + } + } + /** + * Look up the GTyoe from a type name. If the type does not exist, + * return 0. + * + * @param string $name The type name. + * + * @return int + */ + public static function typeFromName(string $name): int + { + return \Jcupitt\Vips\FFI::gobject()->g_type_from_name($name); + } + public static function filenameGetFilename(string $name): string + { + $pointer = \Jcupitt\Vips\FFI::vips()->vips_filename_get_filename($name); + $filename = \FFI::string($pointer); + \Jcupitt\Vips\FFI::glib()->g_free($pointer); + return $filename; + } + public static function filenameGetOptions(string $name): string + { + $pointer = \Jcupitt\Vips\FFI::vips()->vips_filename_get_options($name); + $options = \FFI::string($pointer); + \Jcupitt\Vips\FFI::glib()->g_free($pointer); + return $options; + } +} +/* + * Local variables: + * tab-width: 4 + * c-basic-offset: 4 + * End: + * vim600: expandtab sw=4 ts=4 fdm=marker + * vim<600: expandtab sw=4 ts=4 + */ diff --git a/src/wp-includes/php-vips/src/VipsObject.php b/src/wp-includes/php-vips/src/VipsObject.php new file mode 100644 index 0000000000000..67e645329a3fb --- /dev/null +++ b/src/wp-includes/php-vips/src/VipsObject.php @@ -0,0 +1,175 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/libvips/php-vips + */ +namespace Jcupitt\Vips; + +/** + * This class holds a pointer to a VipsObject (the libvips base class) and + * manages properties. + * + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/libvips/php-vips + */ +abstract class VipsObject extends \Jcupitt\Vips\GObject +{ + /** + * A pointer to the underlying VipsObject. + * + * @internal + */ + private \FFI\CData $pointer; + /** + * A pointer to the underlying GObject. This is the same as the + * VipsObject, just cast. + * + * @internal + */ + private \FFI\CData $gObject; + public function __construct(\FFI\CData $pointer) + { + $this->pointer = \Jcupitt\Vips\FFI::vips()->cast(\Jcupitt\Vips\FFI::ctypes("VipsObject"), $pointer); + $this->gObject = \Jcupitt\Vips\FFI::vips()->cast(\Jcupitt\Vips\FFI::ctypes("GObject"), $pointer); + parent::__construct($pointer); + } + // print a table of all active vipsobjects ... handy for debugging + public static function printAll(): void + { + \Jcupitt\Vips\FFI::vips()->vips_object_print_all(); + } + public function getDescription(): string + { + return \Jcupitt\Vips\FFI::vips()->vips_object_get_description($this->pointer); + } + // get the pspec for a property + // NULL for no such name + // very slow! avoid if possible + // FIXME add a cache for this thing, see code in pyvips + public function getPspec(string $name): ?\FFI\CData + { + $name = str_replace("-", "_", $name); + $pspec_array = \Jcupitt\Vips\FFI::gobject()->new("GParamSpec*[1]"); + $argument_class_array = \Jcupitt\Vips\FFI::vips()->new("VipsArgumentClass*[1]"); + $argument_instance_array = \Jcupitt\Vips\FFI::vips()->new("VipsArgumentInstance*[1]"); + $result = \Jcupitt\Vips\FFI::vips()->vips_object_get_argument($this->pointer, $name, $pspec_array, $argument_class_array, $argument_instance_array); + if ($result != 0) { + $pspec = null; + } else { + /* php-ffi seems to leak if we do the obvious $pspec_array[0] to + * get the return result ... instead, we must make a new pointer + * object and copy the value ourselves + * + * the returns values from vips_object_get_argument() are static, + * so this is safe + */ + $pspec = \Jcupitt\Vips\FFI::gobject()->new("GParamSpec*"); + $to_pointer = \FFI::addr($pspec); + $from_pointer = \FFI::addr($pspec_array); + $size = \FFI::sizeof($from_pointer); + \FFI::memcpy($to_pointer, $from_pointer, $size); + } + return $pspec; + } + // get the type of a property from a VipsObject + // 0 if no such property + public function getType(string $name): int + { + $pspec = $this->getPspec($name); + if (\FFI::isNull($pspec)) { + # need to clear any error, this is horrible + \Jcupitt\Vips\FFI::vips()->vips_error_clear(); + return 0; + } else { + return $pspec->value_type; + } + } + public function getBlurb(string $name): string + { + $pspec = $this->getPspec($name); + return \Jcupitt\Vips\FFI::gobject()->g_param_spec_get_blurb($pspec); + } + public function getArgumentDescription(string $name): string + { + $pspec = $this->getPspec($name); + return \Jcupitt\Vips\FFI::gobject()->g_param_spec_get_description($pspec); + } + /** + * @throws Exception + */ + public function get(string $name) + { + $name = str_replace("-", "_", $name); + $gvalue = new \Jcupitt\Vips\GValue(); + $gvalue->setType($this->getType($name)); + \Jcupitt\Vips\FFI::gobject()->g_object_get_property($this->gObject, $name, $gvalue->pointer); + $value = $gvalue->get(); + \Jcupitt\Vips\Utils::debugLog("get", [$name => var_export($value, \true)]); + return $value; + } + /** + * @throws Exception + */ + public function set(string $name, $value): void + { + \Jcupitt\Vips\Utils::debugLog("set", [$name => $value]); + $name = str_replace("-", "_", $name); + $gvalue = new \Jcupitt\Vips\GValue(); + $gvalue->setType($this->getType($name)); + $gvalue->set($value); + \Jcupitt\Vips\FFI::gobject()->g_object_set_property($this->gObject, $name, $gvalue->pointer); + } + public function setString(string $string_options): bool + { + $result = \Jcupitt\Vips\FFI::vips()->vips_object_set_from_string($this->pointer, $string_options); + return $result == 0; + } + public function unrefOutputs(): void + { + \Jcupitt\Vips\FFI::vips()->vips_object_unref_outputs($this->pointer); + } +} +/* + * Local variables: + * tab-width: 4 + * c-basic-offset: 4 + * End: + * vim600: expandtab sw=4 ts=4 fdm=marker + * vim<600: expandtab sw=4 ts=4 + */ diff --git a/src/wp-includes/php-vips/src/VipsOperation.php b/src/wp-includes/php-vips/src/VipsOperation.php new file mode 100644 index 0000000000000..566ef88263b12 --- /dev/null +++ b/src/wp-includes/php-vips/src/VipsOperation.php @@ -0,0 +1,319 @@ + + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/libvips/php-vips + */ +namespace Jcupitt\Vips; + +/** + * This class holds a pointer to a VipsOperation (the libvips operation base + * class) and manages argument introspection and operation call. + * + * @category Images + * @package Jcupitt\Vips + * @author John Cupitt + * @copyright 2016 John Cupitt + * @license https://opensource.org/licenses/MIT MIT + * @link https://github.com/libvips/php-vips + */ +class VipsOperation extends \Jcupitt\Vips\VipsObject +{ + /** + * A pointer to the underlying VipsOperation. This is the same as the + * GObject, just cast to VipsOperation to help FFI. + * + * @internal + */ + public \FFI\CData $pointer; + /** + * Introspection data for this operation. + */ + public \Jcupitt\Vips\Introspect $introspect; + public function __construct(\FFI\CData $pointer) + { + $this->pointer = \Jcupitt\Vips\FFI::vips()->cast(\Jcupitt\Vips\FFI::ctypes("VipsOperation"), $pointer); + parent::__construct($pointer); + } + /** + * @throws Exception + */ + public static function newFromName($name): \Jcupitt\Vips\VipsOperation + { + $pointer = \Jcupitt\Vips\FFI::vips()->vips_operation_new($name); + if ($pointer == null) { + throw new \Jcupitt\Vips\Exception(); + } + $operation = new \Jcupitt\Vips\VipsOperation($pointer); + return $operation; + } + public function setMatch($name, $match_image, $value): void + { + $flags = $this->introspect->arguments[$name]["flags"]; + $gtype = $this->introspect->arguments[$name]["type"]; + if ($match_image != null) { + if ($gtype == \Jcupitt\Vips\FFI::gtypes("VipsImage")) { + $value = $match_image->imageize($value); + } elseif ($gtype == \Jcupitt\Vips\FFI::gtypes("VipsArrayImage") && is_array($value)) { + $new_value = []; + foreach ($value as $x) { + $new_value[] = $match_image->imageize($x); + } + $value = $new_value; + } + } + # MODIFY args need to be copied before they are set + if (($flags & \Jcupitt\Vips\ArgumentFlags::MODIFY) != 0) { + # logger.debug('copying MODIFY arg %s', name) + # make sure we have a unique copy + $value = $value->copyMemory(); + } + parent::set($name, $value); + } + private static function introspect($name): \Jcupitt\Vips\Introspect + { + static $cache = []; + if (!array_key_exists($name, $cache)) { + $cache[$name] = new \Jcupitt\Vips\Introspect($name); + } + return $cache[$name]; + } + private static function findInside($predicate, $x) + { + if ($predicate($x)) { + return $x; + } + if (is_array($x)) { + foreach ($x as $y) { + $result = self::findInside($predicate, $y); + if ($result != null) { + return $result; + } + } + } + return null; + } + /** + * Is $value a VipsImage. + * + * @param mixed $value The thing to test. + * + * @return bool true if this is a ffi VipsImage*. + * + * @internal + */ + private static function isImagePointer($value): bool + { + return $value instanceof \FFI\CData && \FFI::typeof($value) == \Jcupitt\Vips\FFI::ctypes("VipsImage"); + } + /** + * Wrap up the result of a vips_ call ready to return it to PHP. We do + * two things: + * + * - If the array is a singleton, we strip it off. For example, many + * operations return a single result and there's no sense handling + * this as an array of values, so we transform ['out' => x] -> x. + * + * - Any VipsImage resources are rewrapped as instances of Image. + * + * @param mixed $result Wrap this up. + * + * @return mixed $result, but wrapped up as a php class. + * + * @internal + */ + private static function wrapResult($result) + { + if (!is_array($result)) { + $result = ['x' => $result]; + } + array_walk_recursive($result, function (&$item) { + if (self::isImagePointer($item)) { + $item = new \Jcupitt\Vips\Image($item); + } + }); + if (count($result) === 1) { + $result = array_shift($result); + } + return $result; + } + /** + * Call any vips operation. The final element of $arguments can be + * (but doesn't have to be) an array of options to pass to the operation. + * + * We can't have a separate arg for the options since this will be run from + * __call(), which cannot know which args are required and which are + * optional. See call() below for a version with the options broken out. + * + * @param string $operation_name The operation name. + * @param Image|null $instance The instance this operation is being invoked + * from. + * @param array $arguments An array of arguments to pass to the + * operation. + * + * @throws Exception + * + * @return mixed The result(s) of the operation. + */ + public static function callBase(string $operation_name, ?\Jcupitt\Vips\Image $instance, array $arguments) + { + \Jcupitt\Vips\Utils::debugLog($operation_name, ['instance' => $instance, 'arguments' => $arguments]); + $operation = self::newFromName($operation_name); + $operation->introspect = self::introspect($operation_name); + $introspect = $operation->introspect; + /* the first image argument is the thing we expand constants to + * match ... look inside tables for images, since we may be passing + * an array of images as a single param. + */ + if ($instance != null) { + $match_image = $instance; + } else { + $match_image = self::findInside(fn($x) => $x instanceof \Jcupitt\Vips\Image, $arguments); + } + /* Because of the way php callStatic works, we can sometimes be given + * an instance even when no instance was given. + * + * We must loop over the required args and set them from the supplied + * args, using instance if required, and only check the nargs after + * this pass. + */ + $n_required = count($introspect->required_input); + $n_supplied = count($arguments); + $n_used = 0; + foreach ($introspect->required_input as $name) { + if ($name == $introspect->member_this) { + if (!$instance) { + $operation->unrefOutputs(); + throw new \Jcupitt\Vips\Exception("instance argument not supplied"); + } + $operation->setMatch($name, $match_image, $instance); + } elseif ($n_used < $n_supplied) { + $operation->setMatch($name, $match_image, $arguments[$n_used]); + $n_used += 1; + } else { + $operation->unrefOutputs(); + throw new \Jcupitt\Vips\Exception("{$n_required} arguments required, " . "but {$n_supplied} supplied"); + } + } + /* If there's one extra arg and it's an array, use it as our options. + */ + $options = []; + if ($n_supplied == $n_used + 1 && is_array($arguments[$n_used])) { + $options = array_pop($arguments); + $n_supplied -= 1; + } + if ($n_supplied != $n_used) { + $operation->unrefOutputs(); + throw new \Jcupitt\Vips\Exception("{$n_required} arguments required, " . "but {$n_supplied} supplied"); + } + /* set any string options before any args so they can't be + * overridden. + */ + if (array_key_exists("string_options", $options)) { + $string_options = $options["string_options"]; + unset($options["string_options"]); + $operation->setString($string_options); + } + /* Set optional. + */ + foreach ($options as $name => $value) { + $name = str_replace("-", "_", $name); + if (!in_array($name, $introspect->optional_input) && !in_array($name, $introspect->optional_output)) { + $operation->unrefOutputs(); + throw new \Jcupitt\Vips\Exception("optional argument '{$name}' does not exist"); + } + $operation->setMatch($name, $match_image, $value); + } + /* Build the operation + */ + $pointer = \Jcupitt\Vips\FFI::vips()->vips_cache_operation_build($operation->pointer); + if ($pointer == null) { + $operation->unrefOutputs(); + throw new \Jcupitt\Vips\Exception(); + } + $operation = new \Jcupitt\Vips\VipsOperation($pointer); + $operation->introspect = $introspect; + # TODO .. need to attach input refs to output, see _find_inside in + # pyvips + /* Fetch required output args (and modified input args). + */ + $result = []; + foreach ($introspect->required_output as $name) { + $result[$name] = $operation->get($name); + } + /* Any optional output args. + */ + $option_keys = array_keys($options); + foreach ($introspect->optional_output as $name) { + $name = str_replace("-", "_", $name); + if (in_array($name, $option_keys)) { + $result[$name] = $operation->get($name); + } + } + /* Free any outputs we've not used. + */ + $operation->unrefOutputs(); + $result = self::wrapResult($result); + \Jcupitt\Vips\Utils::debugLog($operation_name, ['result' => var_export($result, \true)]); + return $result; + } + /** + * Call any vips operation, with an explicit set of options. This is more + * convenient than callBase() if you have a set of known options. + * + * @param string $name The operation name. + * @param Image|null $instance The instance this operation is being invoked + * from. + * @param array $arguments An array of arguments to pass to the + * operation. + * @param array $options An array of optional arguments to pass to + * the operation. + * + * @throws Exception + * + * @return mixed The result(s) of the operation. + */ + public static function call(string $name, ?\Jcupitt\Vips\Image $instance, array $arguments, array $options = []) + { + return self::callBase($name, $instance, array_merge($arguments, [$options])); + } +} +/* + * Local variables: + * tab-width: 4 + * c-basic-offset: 4 + * End: + * vim600: expandtab sw=4 ts=4 fdm=marker + * vim<600: expandtab sw=4 ts=4 + */ diff --git a/src/wp-includes/php-vips/third-party/Psr/Log/AbstractLogger.php b/src/wp-includes/php-vips/third-party/Psr/Log/AbstractLogger.php new file mode 100644 index 0000000000000..5966d07d9cd92 --- /dev/null +++ b/src/wp-includes/php-vips/third-party/Psr/Log/AbstractLogger.php @@ -0,0 +1,15 @@ +logger = $logger; + } +} diff --git a/src/wp-includes/php-vips/third-party/Psr/Log/LoggerInterface.php b/src/wp-includes/php-vips/third-party/Psr/Log/LoggerInterface.php new file mode 100644 index 0000000000000..ab74b336a74d6 --- /dev/null +++ b/src/wp-includes/php-vips/third-party/Psr/Log/LoggerInterface.php @@ -0,0 +1,90 @@ +log(LogLevel::EMERGENCY, $message, $context); + } + /** + * Action must be taken immediately. + * + * Example: Entire website down, database unavailable, etc. This should + * trigger the SMS alerts and wake you up. + */ + public function alert(string|\Stringable $message, array $context = []): void + { + $this->log(LogLevel::ALERT, $message, $context); + } + /** + * Critical conditions. + * + * Example: Application component unavailable, unexpected exception. + */ + public function critical(string|\Stringable $message, array $context = []): void + { + $this->log(LogLevel::CRITICAL, $message, $context); + } + /** + * Runtime errors that do not require immediate action but should typically + * be logged and monitored. + */ + public function error(string|\Stringable $message, array $context = []): void + { + $this->log(LogLevel::ERROR, $message, $context); + } + /** + * Exceptional occurrences that are not errors. + * + * Example: Use of deprecated APIs, poor use of an API, undesirable things + * that are not necessarily wrong. + */ + public function warning(string|\Stringable $message, array $context = []): void + { + $this->log(LogLevel::WARNING, $message, $context); + } + /** + * Normal but significant events. + */ + public function notice(string|\Stringable $message, array $context = []): void + { + $this->log(LogLevel::NOTICE, $message, $context); + } + /** + * Interesting events. + * + * Example: User logs in, SQL logs. + */ + public function info(string|\Stringable $message, array $context = []): void + { + $this->log(LogLevel::INFO, $message, $context); + } + /** + * Detailed debug information. + */ + public function debug(string|\Stringable $message, array $context = []): void + { + $this->log(LogLevel::DEBUG, $message, $context); + } + /** + * Logs with an arbitrary level. + * + * @param mixed $level + * + * @throws \Psr\Log\InvalidArgumentException + */ + abstract public function log($level, string|\Stringable $message, array $context = []): void; +} diff --git a/src/wp-includes/php-vips/third-party/Psr/Log/NullLogger.php b/src/wp-includes/php-vips/third-party/Psr/Log/NullLogger.php new file mode 100644 index 0000000000000..bb7e7b79a561f --- /dev/null +++ b/src/wp-includes/php-vips/third-party/Psr/Log/NullLogger.php @@ -0,0 +1,26 @@ +logger) { }` + * blocks. + */ +class NullLogger extends AbstractLogger +{ + /** + * Logs with an arbitrary level. + * + * @param mixed[] $context + * + * @throws \Psr\Log\InvalidArgumentException + */ + public function log($level, string|\Stringable $message, array $context = []): void + { + // noop + } +} diff --git a/tests/phpstan/base.neon b/tests/phpstan/base.neon index 863d2b684d0ac..5e5380199c28c 100644 --- a/tests/phpstan/base.neon +++ b/tests/phpstan/base.neon @@ -238,6 +238,7 @@ parameters: - ../../src/wp-includes/ID3 - ../../src/wp-includes/IXR - ../../src/wp-includes/PHPMailer + - ../../src/wp-includes/php-vips - ../../src/wp-includes/Requests - ../../src/wp-includes/SimplePie - ../../src/wp-includes/Text diff --git a/tools/php-vips/README.md b/tools/php-vips/README.md new file mode 100644 index 0000000000000..04a390a484c7d --- /dev/null +++ b/tools/php-vips/README.md @@ -0,0 +1,58 @@ +# php-vips Installer + +Bundles the [libvips/php-vips](https://github.com/libvips/php-vips) library into WordPress Core at `src/wp-includes/php-vips/`. + +The installer fetches the package, scopes its PSR-3 dependency (`Psr\Log\*`) under `WordPress\VipsDependencies\*` using [PHP-Scoper](https://github.com/humbug/php-scoper) to avoid conflicts with plugin-bundled versions, and generates a manual autoloader. + +`Jcupitt\Vips\*` is deliberately **not** scoped, so plugins that ship the same library keep working against it. + +## Prerequisites + +- PHP +- Composer +- Git +- curl + +## Usage + +Run from the WordPress development repository root: + +```bash +# Install a specific release version +bash tools/php-vips/installer.sh --version=v2.6.1 + +# Install from a branch +bash tools/php-vips/installer.sh --branch=master +``` + +You must specify either `--version` or `--branch` (not both). A bare version number is also accepted and gets the `v` prefix the repository uses for release tags. + +## What It Does + +1. Clones the package from GitHub (shallow clone of the specified ref). +2. Runs `composer install --no-dev` to fetch dependencies. +3. Downloads PHP-Scoper and scopes `Psr\Log\*` to `WordPress\VipsDependencies\*`. +4. Copies the unscoped php-vips source to `src/` and the scoped interfaces to `third-party/Psr/Log/`. +5. Generates `autoload.php` with a PSR-4 autoloader. +6. Validates the output. + +## Output Structure + +``` +src/wp-includes/php-vips/ +├── autoload.php # Generated autoloader +├── LICENSE.txt # php-vips license +├── src/ # php-vips source (Jcupitt\Vips\*) +└── third-party/ # Scoped dependencies (WordPress\VipsDependencies\*) + └── Psr/ + └── Log/ +``` + +## Support Files + +- **`scoper.inc.php`** — PHP-Scoper configuration. Defines the scoping prefix and excludes the php-vips namespace. + +## Notes + +- The installer assumes `psr/log` is the only Composer dependency, because the scoped output is copied to a fixed `third-party/Psr/Log` path. It fails loudly if upstream adds another dependency, so the mapping can be updated deliberately. +- `src/wp-includes/php-vips/` is excluded from PHPCS and PHPStan, matching the other bundled libraries. diff --git a/tools/php-vips/installer.sh b/tools/php-vips/installer.sh new file mode 100755 index 0000000000000..57b6a871873db --- /dev/null +++ b/tools/php-vips/installer.sh @@ -0,0 +1,331 @@ +#!/usr/bin/env bash +# +# Installer script for bundling libvips/php-vips into WordPress Core. +# +# Fetches the package, scopes its PSR-3 dependency (Psr\Log\*) via PHP-Scoper, +# generates a manual autoloader, and places everything into +# src/wp-includes/php-vips/. +# +# Usage: +# bash tools/php-vips/installer.sh --version=2.6.1 +# bash tools/php-vips/installer.sh --branch=master +# + +set -euo pipefail + +# ----------------------------------------------------------------------------- +# Configuration +# ----------------------------------------------------------------------------- + +# 0.18.19 or newer is required to run under PHP 8.5. Earlier versions fail to +# parse every PHP file there: the bundled nikic/php-parser triggers a +# deprecation, and PHP-Scoper's error handler turns deprecations into +# exceptions. +SCOPER_VERSION="0.18.19" +SCOPER_URL="https://github.com/humbug/php-scoper/releases/download/${SCOPER_VERSION}/php-scoper.phar" +GITHUB_REPO="https://github.com/libvips/php-vips.git" + +TARGET_DIR="src/wp-includes/php-vips" +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +# ----------------------------------------------------------------------------- +# Parse arguments +# ----------------------------------------------------------------------------- + +VERSION="" +BRANCH="" + +for arg in "$@"; do + case "$arg" in + --version=*) + VERSION="${arg#--version=}" + ;; + --branch=*) + BRANCH="${arg#--branch=}" + ;; + --help|-h) + echo "Usage: $0 [--version=X.Y.Z | --branch=BRANCH]" + echo "" + echo "Options:" + echo " --version=X.Y.Z Fetch a specific release version" + echo " --branch=BRANCH Fetch from a branch" + echo "" + echo "Must be run from the WordPress development repository root." + exit 0 + ;; + *) + echo "Error: Unknown argument: $arg" + echo "Run '$0 --help' for usage." + exit 1 + ;; + esac +done + +if [ -n "$VERSION" ] && [ -n "$BRANCH" ]; then + echo "Error: Cannot specify both --version and --branch." + exit 1 +fi + +if [ -z "$VERSION" ] && [ -z "$BRANCH" ]; then + echo "Error: Must specify either --version=X.Y.Z or --branch=BRANCH." + exit 1 +fi + +# ----------------------------------------------------------------------------- +# Prerequisites +# ----------------------------------------------------------------------------- + +check_command() { + if ! command -v "$1" &> /dev/null; then + echo "Error: '$1' is required but not found in PATH." + exit 1 + fi +} + +check_command php +check_command composer +check_command git +check_command curl + +# Verify we're running from the repo root. +if [ ! -d "src/wp-includes" ]; then + echo "Error: This script must be run from the WordPress development repository root." + exit 1 +fi + +echo "==> Starting php-vips installer..." + +# ----------------------------------------------------------------------------- +# Temp directory (cleaned on exit) +# ----------------------------------------------------------------------------- + +TEMP_DIR="$(mktemp -d)" +trap 'rm -rf "$TEMP_DIR"' EXIT + +echo "==> Using temp directory: $TEMP_DIR" + +# ----------------------------------------------------------------------------- +# Fetch package +# ----------------------------------------------------------------------------- + +if [ -n "$BRANCH" ]; then + REF="$BRANCH" + echo "==> Cloning branch '$REF' from $GITHUB_REPO..." +else + REF="$VERSION" + echo "==> Cloning tag '$REF' from $GITHUB_REPO..." +fi + +if ! git clone --depth 1 --branch "$REF" "$GITHUB_REPO" "$TEMP_DIR/package" 2>/dev/null; then + # Release tags in the php-vips repository are prefixed with "v", so also + # accept a bare version number. + case "$REF" in + v*) + echo "Error: Could not clone ref '$REF' from $GITHUB_REPO." + exit 1 + ;; + *) + echo "==> Ref '$REF' not found, retrying with 'v${REF}'..." + REF="v${REF}" + git clone --depth 1 --branch "$REF" "$GITHUB_REPO" "$TEMP_DIR/package" + ;; + esac +fi + +echo "==> Installing Composer dependencies..." +# --ignore-platform-reqs: only the source is needed here, and php-vips requires +# ext-ffi, which the machine running the installer may not have. +composer install --no-dev --no-interaction --ignore-platform-reqs --working-dir="$TEMP_DIR/package" + +VENDOR_DIR="$TEMP_DIR/package/vendor" + +if [ ! -d "$VENDOR_DIR" ]; then + echo "Error: vendor directory not found at $VENDOR_DIR" + exit 1 +fi + +# The scoped dependencies are copied to a fixed third-party/Psr/Log path below, +# so this installer assumes psr/log is the only dependency. Fail loudly if +# upstream adds another one, so the mapping is updated deliberately. +UNEXPECTED="$(find "$VENDOR_DIR" -mindepth 2 -maxdepth 2 -type d \ + -not -path "$VENDOR_DIR/composer*" \ + -not -path "$VENDOR_DIR/psr*" | head -5)" + +if [ -n "$UNEXPECTED" ]; then + echo "Error: Unexpected Composer dependencies found:" + echo "$UNEXPECTED" + echo "Update this installer to map them into third-party/." + exit 1 +fi + +echo "==> Package fetched successfully." + +# ----------------------------------------------------------------------------- +# Clean target directory +# ----------------------------------------------------------------------------- + +if [ -d "$TARGET_DIR" ]; then + echo "==> Removing existing $TARGET_DIR..." + rm -rf "$TARGET_DIR" +fi + +# ----------------------------------------------------------------------------- +# Scope dependencies with PHP-Scoper +# ----------------------------------------------------------------------------- + +SCOPER_PHAR="$TEMP_DIR/php-scoper.phar" + +echo "==> Downloading PHP-Scoper ${SCOPER_VERSION}..." +curl -fsSL "$SCOPER_URL" -o "$SCOPER_PHAR" +chmod +x "$SCOPER_PHAR" + +# Copy scoper config into temp dir. +cp "$SCRIPT_DIR/scoper.inc.php" "$TEMP_DIR/scoper.inc.php" + +SCOPED_DIR="$TEMP_DIR/scoped" + +echo "==> Running PHP-Scoper..." + +SCOPER_LOG="$TEMP_DIR/scoper.log" + +# E_DEPRECATED is suppressed because PHP-Scoper's error handler turns +# deprecations into exceptions. A deprecation raised by the bundled +# nikic/php-parser on a newer PHP would otherwise make every file fail to parse. +php -d error_reporting='E_ALL & ~E_DEPRECATED' "$SCOPER_PHAR" add-prefix \ + --working-dir="$TEMP_DIR/package" \ + --config="$TEMP_DIR/scoper.inc.php" \ + --output-dir="$SCOPED_DIR" \ + --force \ + --no-interaction \ + 2>&1 | tee "$SCOPER_LOG" + +# PHP-Scoper exits 0 even when it failed to parse every single file, and still +# reports "Successfully prefixed N files". It writes the files either way, so +# the only reliable signal that scoping actually happened is the error log. +FAILED_FILES="$( grep -c '\[NO\]' "$SCOPER_LOG" || true )" + +if [ "$FAILED_FILES" -gt 0 ]; then + echo "Error: PHP-Scoper could not parse $FAILED_FILES file(s):" + grep '\[NO\]' "$SCOPER_LOG" | head -20 + exit 1 +fi + +echo "==> Scoping complete." + +# ----------------------------------------------------------------------------- +# Copy files to target +# ----------------------------------------------------------------------------- + +echo "==> Copying files to $TARGET_DIR..." + +mkdir -p "$TARGET_DIR/src" +mkdir -p "$TARGET_DIR/third-party/Psr/Log" + +# php-vips itself is not scoped. +cp -R "$SCOPED_DIR/src/." "$TARGET_DIR/src/" + +# Scoped PSR-3 interfaces. +cp -R "$SCOPED_DIR/vendor/psr/log/src/." "$TARGET_DIR/third-party/Psr/Log/" + +# Licenses. +cp "$TEMP_DIR/package/LICENSE.txt" "$TARGET_DIR/LICENSE.txt" +cp "$VENDOR_DIR/psr/log/LICENSE" "$TARGET_DIR/third-party/Psr/Log/LICENSE" + +# ----------------------------------------------------------------------------- +# Generate autoload.php +# ----------------------------------------------------------------------------- + +echo "==> Generating autoload.php..." + +cat > "$TARGET_DIR/autoload.php" << 'AUTOLOAD_PHP' + autoload.php generated." + +# ----------------------------------------------------------------------------- +# Validate output +# ----------------------------------------------------------------------------- + +echo "==> Validating output..." + +ERRORS=0 + +for path in \ + "$TARGET_DIR/autoload.php" \ + "$TARGET_DIR/src/Image.php" \ + "$TARGET_DIR/third-party/Psr/Log/LoggerInterface.php"; do + if [ ! -f "$path" ]; then + echo "Error: Missing expected file: $path" + ERRORS=$((ERRORS + 1)) + fi +done + +# The PSR-3 interfaces must carry the prefix, and php-vips must not. +if ! grep -q 'namespace WordPress\\VipsDependencies\\Psr\\Log;' "$TARGET_DIR/third-party/Psr/Log/LoggerInterface.php"; then + echo "Error: Psr\\Log was not scoped as expected." + ERRORS=$((ERRORS + 1)) +fi + +if ! grep -q 'namespace Jcupitt\\Vips;' "$TARGET_DIR/src/Image.php"; then + echo "Error: Jcupitt\\Vips was unexpectedly scoped." + ERRORS=$((ERRORS + 1)) +fi + +# php-vips must reference the scoped logger, not the global one. +if ! grep -q 'WordPress\\VipsDependencies\\Psr\\Log\\LoggerInterface' "$TARGET_DIR/src/Config.php"; then + echo "Error: php-vips does not reference the scoped Psr\\Log interface." + ERRORS=$((ERRORS + 1)) +fi + +if [ "$ERRORS" -gt 0 ]; then + echo "==> Validation failed with $ERRORS error(s)." + exit 1 +fi + +echo "==> Validation passed." +echo "==> php-vips installed into $TARGET_DIR." diff --git a/tools/php-vips/scoper.inc.php b/tools/php-vips/scoper.inc.php new file mode 100644 index 0000000000000..e22ea29bd7d9d --- /dev/null +++ b/tools/php-vips/scoper.inc.php @@ -0,0 +1,53 @@ + 'WordPress\\VipsDependencies', + + 'finders' => array( + // Include all PHP files in vendor (dependencies) so their namespaces get scoped. + Finder::create() + ->files() + ->ignoreVCS( true ) + ->notName( '/LICENSE|.*\\.md|.*\\.dist|Makefile/' ) + ->exclude( array( 'composer', 'doc', 'test', 'test_old', 'tests', 'Tests', 'vendor-bin' ) ) + ->in( 'vendor' ), + + // Include the php-vips source files so `use` statements referencing scoped + // dependency namespaces get updated. The php-vips namespace is excluded below, + // so its `namespace` declarations stay unchanged. + Finder::create() + ->files() + ->ignoreVCS( true ) + ->name( '*.php' ) + ->in( 'src' ), + ), + + 'exclude-namespaces' => array( + // The php-vips namespace must not be scoped. + 'Jcupitt\\Vips', + ), + + 'exclude-files' => array(), + + 'exclude-constants' => array( + // Preserve WordPress-compatible constants. + '/^ABSPATH$/', + '/^WPINC$/', + ), + + 'exclude-functions' => array(), + + 'patchers' => array(), +); From afe4630a8462e1a8da9ab8b3260750946b7312a9 Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Fri, 25 Sep 2026 15:04:15 -0600 Subject: [PATCH 26/84] Local env: Default the php-vips installer to the latest release --- tools/php-vips/README.md | 9 +++++++-- tools/php-vips/installer.sh | 38 +++++++++++++++++++++++++++++-------- 2 files changed, 37 insertions(+), 10 deletions(-) diff --git a/tools/php-vips/README.md b/tools/php-vips/README.md index 04a390a484c7d..d13d97e36f7c2 100644 --- a/tools/php-vips/README.md +++ b/tools/php-vips/README.md @@ -18,14 +18,19 @@ The installer fetches the package, scopes its PSR-3 dependency (`Psr\Log\*`) und Run from the WordPress development repository root: ```bash -# Install a specific release version +# Install the latest release +bash tools/php-vips/installer.sh + +# Install a specific release bash tools/php-vips/installer.sh --version=v2.6.1 # Install from a branch bash tools/php-vips/installer.sh --branch=master ``` -You must specify either `--version` or `--branch` (not both). A bare version number is also accepted and gets the `v` prefix the repository uses for release tags. +With no arguments the newest release tag is resolved from the remote and installed. Prefer that over a branch, because it pins the bundled code to a released version. + +`--version` and `--branch` are mutually exclusive. A bare version number is also accepted and gets the `v` prefix the repository uses for release tags. ## What It Does diff --git a/tools/php-vips/installer.sh b/tools/php-vips/installer.sh index 57b6a871873db..a492e5d0804f0 100755 --- a/tools/php-vips/installer.sh +++ b/tools/php-vips/installer.sh @@ -7,9 +7,12 @@ # src/wp-includes/php-vips/. # # Usage: -# bash tools/php-vips/installer.sh --version=2.6.1 +# bash tools/php-vips/installer.sh +# bash tools/php-vips/installer.sh --version=v2.6.1 # bash tools/php-vips/installer.sh --branch=master # +# Without --version or --branch, the latest release is installed. +# set -euo pipefail @@ -49,8 +52,8 @@ for arg in "$@"; do echo "Options:" echo " --version=X.Y.Z Fetch a specific release version" echo " --branch=BRANCH Fetch from a branch" - echo "" - echo "Must be run from the WordPress development repository root." + echo "" echo "With neither option, the latest release is installed." + echo "" echo "Must be run from the WordPress development repository root." exit 0 ;; *) @@ -66,11 +69,6 @@ if [ -n "$VERSION" ] && [ -n "$BRANCH" ]; then exit 1 fi -if [ -z "$VERSION" ] && [ -z "$BRANCH" ]; then - echo "Error: Must specify either --version=X.Y.Z or --branch=BRANCH." - exit 1 -fi - # ----------------------------------------------------------------------------- # Prerequisites # ----------------------------------------------------------------------------- @@ -82,6 +80,16 @@ check_command() { fi } +# Resolves the newest release tag on the remote, e.g. "v2.6.1". +latest_release_tag() { + git ls-remote --tags --refs "$GITHUB_REPO" 2>/dev/null \ + | awk -F/ '{ print $NF }' \ + | grep -E '^v?[0-9]+(\.[0-9]+)*$' \ + | sort -V \ + | tail -n 1 \ + || true +} + check_command php check_command composer check_command git @@ -108,6 +116,20 @@ echo "==> Using temp directory: $TEMP_DIR" # Fetch package # ----------------------------------------------------------------------------- +# Nothing was requested, so fall back to the latest release. +if [ -z "$BRANCH" ] && [ -z "$VERSION" ]; then + echo "==> No version requested, resolving the latest release..." + VERSION="$(latest_release_tag)" + + if [ -z "$VERSION" ]; then + echo "Error: Could not resolve the latest release from $GITHUB_REPO." + echo "Specify one explicitly with --version=X.Y.Z or --branch=BRANCH." + exit 1 + fi + + echo "==> Latest release is $VERSION." +fi + if [ -n "$BRANCH" ]; then REF="$BRANCH" echo "==> Cloning branch '$REF' from $GITHUB_REPO..." From 4d91a7b2c5c12dcfb732068ea663b0b08637183a Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Fri, 25 Sep 2026 15:06:05 -0600 Subject: [PATCH 27/84] Tests: Cover the image editor fallback when libvips is unavailable --- tests/phpunit/includes/mock-image-editor.php | 12 +++++++ tests/phpunit/tests/image/editor.php | 36 ++++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/tests/phpunit/includes/mock-image-editor.php b/tests/phpunit/includes/mock-image-editor.php index ab2e7379fd439..6943036d370f0 100644 --- a/tests/phpunit/includes/mock-image-editor.php +++ b/tests/phpunit/includes/mock-image-editor.php @@ -72,4 +72,16 @@ public function get_size() { } } + /** + * An image editor that always reports itself as unavailable. + * + * Used to test that editor selection falls through to the next implementation. + */ + class WP_Image_Editor_Unavailable_Mock extends WP_Image_Editor_Mock { + + public static function test( $args = array() ) { + return false; + } + } + endif; diff --git a/tests/phpunit/tests/image/editor.php b/tests/phpunit/tests/image/editor.php index 89985af4e67dd..648c391ae9665 100644 --- a/tests/phpunit/tests/image/editor.php +++ b/tests/phpunit/tests/image/editor.php @@ -49,6 +49,42 @@ public function test_get_editor_load_returns_false() { WP_Image_Editor_Mock::$load_return = true; } + /** + * Test that editor selection skips an implementation that reports itself as + * unavailable and uses the next one instead. + */ + public function test_get_editor_skips_unavailable_implementations() { + remove_filter( 'wp_image_editors', array( $this, 'setEngine' ), 10 ); + add_filter( + 'wp_image_editors', + static function () { + return array( 'WP_Image_Editor_Unavailable_Mock', 'WP_Image_Editor_Mock' ); + } + ); + + $editor = wp_get_image_editor( DIR_TESTDATA . '/images/canola.jpg' ); + + $this->assertSame( 'WP_Image_Editor_Mock', get_class( $editor ) ); + } + + /** + * Test that editor selection uses the first implementation that reports itself + * as available, so the fallback above is not skipping the first entry blindly. + */ + public function test_get_editor_uses_the_first_available_implementation() { + remove_filter( 'wp_image_editors', array( $this, 'setEngine' ), 10 ); + add_filter( + 'wp_image_editors', + static function () { + return array( 'WP_Image_Editor_Mock', 'WP_Image_Editor_Unavailable_Mock' ); + } + ); + + $editor = wp_get_image_editor( DIR_TESTDATA . '/images/canola.jpg' ); + + $this->assertSame( 'WP_Image_Editor_Mock', get_class( $editor ) ); + } + /** * Return integer of 95 for testing. */ From 5053415112f8339512850e6795b6f1204e821a21 Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Fri, 25 Sep 2026 15:09:25 -0600 Subject: [PATCH 28/84] Vips: Strip metadata only when the image is resized, matching Imagick --- .../class-wp-image-editor-vips.php | 17 ++++++++++ tests/phpunit/tests/image/editorVips.php | 34 ++++++++++++++++++- 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index 040b31c109abb..9e13539f0627c 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -33,6 +33,16 @@ class WP_Image_Editor_Vips extends WP_Image_Editor { */ protected $original_image; + /** + * Whether the image has been resized or cropped since it was loaded. + * + * Metadata is only stripped on such saves, matching the Imagick editor, so saving + * an image that was merely loaded keeps its metadata. + * + * @var bool + */ + protected $resized = false; + /** * Cache of mime type support checks. * @@ -292,6 +302,7 @@ public function resize( $max_w, $max_h, $crop = false ) { $this->image = $this->image->resize( $h_scale, array( 'vscale' => $v_scale ) ); $this->update_size( $dst_w, $dst_h ); + $this->resized = true; return true; } catch ( Exception $e ) { @@ -429,6 +440,7 @@ public function crop( $src_x, $src_y, $src_w, $src_h, $dst_w = null, $dst_h = nu $this->image = $cropped; $this->update_size( $dst_w, $dst_h ); + $this->resized = true; return true; } catch ( Exception $e ) { @@ -552,6 +564,11 @@ protected function _save( $image, $filename = null, $mime_type = null ) { /** This filter is documented in wp-includes/class-wp-image-editor-imagick.php */ $strip_meta = apply_filters( 'image_strip_meta', true ); + // Only strip when the image was resized or cropped. This matches the Imagick + // editor, which strips during thumbnail generation rather than on every save, + // so saving an image that was merely loaded keeps its metadata. + $strip_meta = $strip_meta && $this->resized; + switch ( $mime_type ) { case 'image/jpeg': $save_options['Q'] = $this->get_quality(); diff --git a/tests/phpunit/tests/image/editorVips.php b/tests/phpunit/tests/image/editorVips.php index a27ad1dfaaadc..a520a1dc811c2 100644 --- a/tests/phpunit/tests/image/editorVips.php +++ b/tests/phpunit/tests/image/editorVips.php @@ -728,7 +728,8 @@ public function test_image_preserves_alpha_on_rotate() { } /** - * Tests that the image_strip_meta filter controls whether metadata is stripped. + * Tests that the image_strip_meta filter controls whether metadata is stripped + * when the image is resized. * * @requires extension exif */ @@ -743,6 +744,8 @@ public function test_image_strip_meta_filter() { $vips_image_editor = new WP_Image_Editor_Vips( $file ); $vips_image_editor->load(); + $this->assertNotWPError( $vips_image_editor->resize( 25, 25 ) ); + $stripped_file = tempnam( get_temp_dir(), 'vips_meta_' ) . '.jpg'; $vips_image_editor->save( $stripped_file ); @@ -757,6 +760,8 @@ public function test_image_strip_meta_filter() { $vips_image_editor = new WP_Image_Editor_Vips( $file ); $vips_image_editor->load(); + $this->assertNotWPError( $vips_image_editor->resize( 25, 25 ) ); + $preserved_file = tempnam( get_temp_dir(), 'vips_meta_' ) . '.jpg'; $vips_image_editor->save( $preserved_file ); @@ -768,6 +773,33 @@ public function test_image_strip_meta_filter() { $this->assertNotEmpty( $preserved['caption'], 'Metadata should be preserved when the filter returns false.' ); } + /** + * Tests that metadata survives a save that does not resize the image. + * + * Metadata is only stripped when the image is resized or cropped, matching the + * Imagick editor, so the filter returning true is not enough on its own. + * + * @requires extension exif + */ + public function test_metadata_is_preserved_when_saving_without_resizing() { + $file = DIR_TESTDATA . '/images/test-image-iptc.jpg'; + + add_filter( 'image_strip_meta', '__return_true' ); + + $vips_image_editor = new WP_Image_Editor_Vips( $file ); + $vips_image_editor->load(); + + $saved_file = tempnam( get_temp_dir(), 'vips_meta_' ) . '.jpg'; + $vips_image_editor->save( $saved_file ); + + remove_filter( 'image_strip_meta', '__return_true' ); + + $saved = wp_read_image_metadata( $saved_file ); + unlink( $saved_file ); + + $this->assertNotEmpty( $saved['caption'], 'Metadata should be preserved when the image is not resized.' ); + } + /** * Tests that a single loaded image can be read more than once. * From 3207cefd56aa661b691eff140d605f7ce2edbe93 Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Fri, 25 Sep 2026 15:14:11 -0600 Subject: [PATCH 29/84] Vips: Document the FFI and libvips requirement --- composer.json | 2 +- src/wp-includes/class-wp-image-editor-vips.php | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 9c69c82c514e5..a02f3a9227ea3 100644 --- a/composer.json +++ b/composer.json @@ -21,7 +21,7 @@ "ext-curl": "*", "ext-dom": "*", "ext-exif": "*", - "ext-ffi": "Required to use the optional WP_Image_Editor_Vips backend", + "ext-ffi": "*", "ext-fileinfo": "*", "ext-filter": "*", "ext-ftp": "*", diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index 9e13539f0627c..cb225c41f07b0 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -14,6 +14,10 @@ /** * WordPress Image Editor Class for Image Manipulation through VIPS * + * Requires the FFI extension with `ffi.enable` turned on, and the libvips shared + * library. Without them, test() reports the editor as unsupported and image editing + * falls back to Imagick or GD. + * * @since 7.2.0 * * @see WP_Image_Editor From 6e7a279491e2ff2959e3d623b33c8dd1286fb6d4 Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Fri, 25 Sep 2026 15:25:25 -0600 Subject: [PATCH 30/84] Tests: Explain what the editor fallback tests distinguish --- tests/phpunit/tests/image/editor.php | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/tests/phpunit/tests/image/editor.php b/tests/phpunit/tests/image/editor.php index 648c391ae9665..0bb472d26f981 100644 --- a/tests/phpunit/tests/image/editor.php +++ b/tests/phpunit/tests/image/editor.php @@ -52,6 +52,9 @@ public function test_get_editor_load_returns_false() { /** * Test that editor selection skips an implementation that reports itself as * unavailable and uses the next one instead. + * + * The editor list puts the unavailable mock first, so WP_Image_Editor_Mock can only + * be returned by skipping past it. */ public function test_get_editor_skips_unavailable_implementations() { remove_filter( 'wp_image_editors', array( $this, 'setEngine' ), 10 ); @@ -68,8 +71,12 @@ static function () { } /** - * Test that editor selection uses the first implementation that reports itself - * as available, so the fallback above is not skipping the first entry blindly. + * Test that editor selection uses the first available implementation, rather than + * skipping ahead to a later one. + * + * The list is the reverse of the test above. Both tests expect WP_Image_Editor_Mock, + * so it is only the ordering that makes them meaningful: together they show the + * chooser inspects every entry, rather than taking the first or the last. */ public function test_get_editor_uses_the_first_available_implementation() { remove_filter( 'wp_image_editors', array( $this, 'setEngine' ), 10 ); From 2f5763d03b5baa484330ddef8cfa9f8679eed30e Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Fri, 25 Sep 2026 15:41:59 -0600 Subject: [PATCH 31/84] Local env: Add the HEIC and AVIF encoders to the VIPS image --- tools/local-env/php-vips/Dockerfile | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/tools/local-env/php-vips/Dockerfile b/tools/local-env/php-vips/Dockerfile index 445a9cea3c7db..d98d7880e9005 100644 --- a/tools/local-env/php-vips/Dockerfile +++ b/tools/local-env/php-vips/Dockerfile @@ -9,11 +9,22 @@ FROM wordpressdevelop/php:${LOCAL_PHP} # extension that performs the loading, and is otherwise only pulled in transitively by # the libvips development packages. # +# The libheif plugins supply the HEIF/AVIF codecs. libvips can decode both formats out of +# the box, but it cannot encode either without an explicit encoder: x265 for HEIC, aomenc +# for AVIF. Without them heifsave fails with "Unsupported compression". The decoders are +# listed as well, so reading does not silently depend on libvips recommending them. +# # FFI is enabled, and the stack size check is disabled because libvips' native call # depth can trip it. RUN set -eux; \ apt-get update; \ - apt-get install -y --no-install-recommends libvips42 libffi-dev; \ + apt-get install -y --no-install-recommends \ + libvips42 \ + libffi-dev \ + libheif-plugin-libde265 \ + libheif-plugin-dav1d \ + libheif-plugin-x265 \ + libheif-plugin-aomenc; \ rm -rf /var/lib/apt/lists/*; \ docker-php-ext-install ffi; \ docker-php-ext-enable ffi; \ From c7dd394098d72ee8975103d1a57c9490451c6f00 Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Fri, 25 Sep 2026 15:41:59 -0600 Subject: [PATCH 32/84] Vips: Fix infinite recursion when loading HEIC and AVIF images --- src/wp-includes/class-wp-image-editor-vips.php | 10 ++++------ src/wp-includes/media.php | 9 ++++++--- 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index cb225c41f07b0..96b6ad655a456 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -220,12 +220,10 @@ public function load() { } // Set the mime type. - $size = wp_getimagesize( $this->file ); - if ( $size ) { - $this->mime_type = $size['mime']; - } else { - $this->mime_type = wp_get_image_mime( $this->file ); - } + // + // This must not use wp_getimagesize(): for HEIC and AVIF files it falls back + // to the editors, which would recurse straight back into load(). + $this->mime_type = wp_get_image_mime( $this->file ); if ( ! $this->mime_type ) { $this->mime_type = $this->default_mime_type; diff --git a/src/wp-includes/media.php b/src/wp-includes/media.php index 1fa29f79a2503..250824a11dd10 100644 --- a/src/wp-includes/media.php +++ b/src/wp-includes/media.php @@ -5999,9 +5999,12 @@ function wp_getimagesize( $filename, ?array &$image_info = null ) { return false; } - // If the editor for HEICs is Imagick, use it to get the image size. - if ( $editor instanceof WP_Image_Editor_Imagick ) { - $size = $editor->get_size(); + // Any editor that claimed HEIC support and successfully loaded the file can + // report the size. This is not limited to Imagick: GD never gets here because it + // does not claim HEIC support, but the VIPS editor does. + $size = $editor->get_size(); + + if ( $size ) { return array( $size['width'], $size['height'], From b397a79b9dcb0fab3d9b58c7906491dc3df8bce2 Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Fri, 25 Sep 2026 16:22:10 -0600 Subject: [PATCH 33/84] Vendor: Record the vendored php-vips ref and commit in the autoloader --- src/wp-includes/php-vips/autoload.php | 2 ++ tools/php-vips/README.md | 1 + tools/php-vips/installer.sh | 12 ++++++++++-- 3 files changed, 13 insertions(+), 2 deletions(-) diff --git a/src/wp-includes/php-vips/autoload.php b/src/wp-includes/php-vips/autoload.php index bd5e8db0f558f..ca4f5d90d2d60 100644 --- a/src/wp-includes/php-vips/autoload.php +++ b/src/wp-includes/php-vips/autoload.php @@ -5,6 +5,8 @@ * This file is generated by tools/php-vips/installer.sh. * Do not edit directly. * + * Vendored from https://github.com/libvips/php-vips.git at v2.6.1 (6dbba1bb3a4ba1e39edb71016a2aa6da5bff32ee). + * * @package WordPress * @subpackage Image_Editor * @since 7.2.0 diff --git a/tools/php-vips/README.md b/tools/php-vips/README.md index d13d97e36f7c2..19ff95035e703 100644 --- a/tools/php-vips/README.md +++ b/tools/php-vips/README.md @@ -61,3 +61,4 @@ src/wp-includes/php-vips/ - The installer assumes `psr/log` is the only Composer dependency, because the scoped output is copied to a fixed `third-party/Psr/Log` path. It fails loudly if upstream adds another dependency, so the mapping can be updated deliberately. - `src/wp-includes/php-vips/` is excluded from PHPCS and PHPStan, matching the other bundled libraries. +- The generated `autoload.php` records the repository, ref and commit the bundle was built from. diff --git a/tools/php-vips/installer.sh b/tools/php-vips/installer.sh index a492e5d0804f0..9d0915d540c0d 100755 --- a/tools/php-vips/installer.sh +++ b/tools/php-vips/installer.sh @@ -154,6 +154,9 @@ if ! git clone --depth 1 --branch "$REF" "$GITHUB_REPO" "$TEMP_DIR/package" 2>/d esac fi +# Record the exact commit, so the generated autoloader states what was vendored. +PACKAGE_SHA="$( git -C "$TEMP_DIR/package" rev-parse HEAD )" + echo "==> Installing Composer dependencies..." # --ignore-platform-reqs: only the source is needed here, and php-vips requires # ext-ffi, which the machine running the installer may not have. @@ -259,7 +262,7 @@ cp "$VENDOR_DIR/psr/log/LICENSE" "$TARGET_DIR/third-party/Psr/Log/LICENSE" echo "==> Generating autoload.php..." -cat > "$TARGET_DIR/autoload.php" << 'AUTOLOAD_PHP' +cat > "$TARGET_DIR/autoload.php" << AUTOLOAD_HEADER "$TARGET_DIR/autoload.php" << 'AUTOLOAD_PHP' * This file is generated by tools/php-vips/installer.sh. * Do not edit directly. * + * Vendored from ${GITHUB_REPO} at ${REF} (${PACKAGE_SHA}). + * * @package WordPress * @subpackage Image_Editor * @since 7.2.0 */ +AUTOLOAD_HEADER + +cat >> "$TARGET_DIR/autoload.php" << 'AUTOLOAD_BODY' spl_autoload_register( static function ( $class_name ) { // Namespace prefix for php-vips. @@ -305,7 +313,7 @@ spl_autoload_register( } } ); -AUTOLOAD_PHP +AUTOLOAD_BODY echo "==> autoload.php generated." From 939c31e60cd6b2bd48813779fe178cef2e481fb9 Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Fri, 25 Sep 2026 16:22:10 -0600 Subject: [PATCH 34/84] Local env: Give the CLI container libvips too --- docker-compose.vips.yml | 14 +++++++++++++ tools/local-env/cli-vips/Dockerfile | 32 +++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 tools/local-env/cli-vips/Dockerfile diff --git a/docker-compose.vips.yml b/docker-compose.vips.yml index 5fa1628e64690..24cfba2fbc700 100644 --- a/docker-compose.vips.yml +++ b/docker-compose.vips.yml @@ -15,3 +15,17 @@ services: # `up` only builds when the image is missing, and the base image is always present, # so without this the VIPS image would never be built and the VIPS tests would skip. pull_policy: build + + cli: + # WP-CLI image operations (`wp media regenerate`, `wp media import`) run in this + # container, so it needs the same backend. It gets its own tag for the same reason as + # the php service above. + image: wordpressdevelop/cli-vips:${LOCAL_PHP-latest} + + build: + context: . + dockerfile: tools/local-env/cli-vips/Dockerfile + args: + LOCAL_PHP: ${LOCAL_PHP-latest} + + pull_policy: build diff --git a/tools/local-env/cli-vips/Dockerfile b/tools/local-env/cli-vips/Dockerfile new file mode 100644 index 0000000000000..75dd9340d8555 --- /dev/null +++ b/tools/local-env/cli-vips/Dockerfile @@ -0,0 +1,32 @@ +ARG LOCAL_PHP=latest +FROM wordpressdevelop/cli:${LOCAL_PHP} + +# Everything is installed in a single layer on purpose. The published base image sits at +# the overlayfs layering limit, so a second layer of our own is enough to make the build +# fail with "max depth exceeded". +# +# This base image does not compile FFI in, unlike the php image, so libffi-dev is needed +# to build the extension here. +# +# libvips42 is the library the binding loads. The libheif plugins supply the HEIF/AVIF +# codecs: libvips can decode both formats out of the box, but it cannot encode either +# without an explicit encoder, so x265 (HEIC) and aomenc (AVIF) are required for saving. +# +# FFI is enabled, and the stack size check is disabled because libvips' native call depth +# can trip it. +RUN set -eux; \ + apt-get update; \ + apt-get install -y --no-install-recommends \ + libvips42 \ + libffi-dev \ + libheif-plugin-libde265 \ + libheif-plugin-dav1d \ + libheif-plugin-x265 \ + libheif-plugin-aomenc; \ + rm -rf /var/lib/apt/lists/*; \ + docker-php-ext-install ffi; \ + docker-php-ext-enable ffi; \ + { \ + echo 'ffi.enable=1'; \ + echo 'zend.max_allowed_stack_size=-1'; \ + } > /usr/local/etc/php/conf.d/vips-ffi.ini From 3cac63b5e9c79c4988da858f2b690656edc5f431 Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Fri, 25 Sep 2026 16:38:12 -0600 Subject: [PATCH 35/84] Vips: Handle lossless WebP quality like the other editors --- .../class-wp-image-editor-vips.php | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index 96b6ad655a456..f10ed96989e07 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -47,6 +47,13 @@ class WP_Image_Editor_Vips extends WP_Image_Editor { */ protected $resized = false; + /** + * Whether the image is a lossless WebP that must be re-saved losslessly. + * + * @var bool + */ + protected $lossless = false; + /** * Cache of mime type support checks. * @@ -238,6 +245,36 @@ public function load() { } } + /** + * Sets Image Compression quality on a 1-100% scale. + * + * @since 7.2.0 + * + * @param int $quality Compression Quality. Range: [1,100]. + * @param array $dims Optional. Image dimensions array with 'width' and 'height' keys. + * @return true|WP_Error True if set successfully; WP_Error on failure. + */ + public function set_quality( $quality = null, $dims = array() ) { + $quality_result = parent::set_quality( $quality, $dims ); + + if ( is_wp_error( $quality_result ) ) { + return $quality_result; + } + + // A lossless WebP has no quality to preserve, so it is re-saved losslessly at 100, + // matching the GD and Imagick editors. + if ( 'image/webp' === $this->mime_type ) { + $webp_info = wp_get_webp_info( $this->file ); + + if ( 'lossless' === $webp_info['type'] ) { + $this->lossless = true; + parent::set_quality( 100 ); + } + } + + return true; + } + /** * Sets or updates current image size. * @@ -589,6 +626,10 @@ protected function _save( $image, $filename = null, $mime_type = null ) { case 'image/webp': $save_options['Q'] = $this->get_quality(); $save_options['strip'] = $strip_meta; + + if ( $this->lossless ) { + $save_options['lossless'] = true; + } break; case 'image/gif': From 1f7fb41d366da0c8c42415b3d4fcef358b9dfbd1 Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Fri, 25 Sep 2026 16:39:42 -0600 Subject: [PATCH 36/84] Vips: Probe encoder support in memory instead of through a temp file --- .../class-wp-image-editor-vips.php | 42 ++++--------------- 1 file changed, 9 insertions(+), 33 deletions(-) diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index f10ed96989e07..35f26f508419c 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -149,42 +149,18 @@ public static function supports_mime_type( $mime_type ) { try { $test_image = Jcupitt\Vips\Image::black( 1, 1 ); - // libvips selects the encoder from the file suffix, so the probe is written - // to a suffixed file. tempnam() creates the unsuffixed file itself, and both - // are removed once the probe has run. - $temp_file = tempnam( sys_get_temp_dir(), 'vips_test_' ); + // libvips picks the encoder from the suffix, so the buffer is given one. + // Nothing is written to disk, so there is no temp file to clean up. + $buffer = $test_image->writeToBuffer( '.' . $target_extension ); - if ( false === $temp_file ) { - self::$mime_support_cache[ $mime_type ] = false; - - return false; - } - - $probe_file = $temp_file . '.' . $target_extension; - - try { - $test_image->writeToFile( $probe_file ); - $supported = file_exists( $probe_file ) && filesize( $probe_file ) > 0; - } catch ( Exception $write_error ) { - $supported = false; - } finally { - if ( file_exists( $temp_file ) ) { - unlink( $temp_file ); - } - - if ( file_exists( $probe_file ) ) { - unlink( $probe_file ); - } - } - - self::$mime_support_cache[ $mime_type ] = $supported; - - return $supported; + $supported = ! empty( $buffer ); } catch ( Exception $e ) { - self::$mime_support_cache[ $mime_type ] = false; - - return false; + $supported = false; } + + self::$mime_support_cache[ $mime_type ] = $supported; + + return $supported; } /** From a645c46a91c448659925e8cebad50c4f1da3612f Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Fri, 25 Sep 2026 16:39:42 -0600 Subject: [PATCH 37/84] Vips: Apply the EXIF orientation with autorot() so no stale tag remains --- .../class-wp-image-editor-vips.php | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index 35f26f508419c..713cd85497d14 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -499,6 +499,57 @@ public function rotate( $angle ) { } } + /** + * Checks if the image has an EXIF Orientation tag and rotates it if needed. + * + * @since 7.2.0 + * + * @return bool|WP_Error True if the image was rotated. False if not rotated. + * WP_Error if error while rotating. + */ + public function maybe_exif_rotate() { + $orientation = null; + + if ( 'image/jpeg' === $this->mime_type ) { + $exif_data = @exif_read_data( $this->file ); + + if ( ! empty( $exif_data['Orientation'] ) ) { + $orientation = (int) $exif_data['Orientation']; + } + } + + /** This filter is documented in wp-includes/class-wp-image-editor.php */ + $orientation = apply_filters( 'wp_image_maybe_exif_rotate', $orientation, $this->file ); + + if ( ! $orientation || 1 === $orientation ) { + return false; + } + + /* + * libvips applies all eight EXIF orientations itself, and clears the orientation + * field as it goes. Rotating or flipping per the parent's switch would leave that + * field in place, so the saved image would be oriented a second time when it is + * loaded again. This is the "EXIF Orientation can be reset afterwards" requirement + * the parent documents. + */ + if ( ! is_callable( array( $this->image, 'autorot' ) ) ) { + return new WP_Error( 'write_exif_error', __( 'The image cannot be rotated because the embedded meta data cannot be updated.' ) ); + } + + try { + $this->image = $this->image->autorot(); + } catch ( Exception $e ) { + return new WP_Error( 'image_rotate_error', $e->getMessage() ); + } + + $result = $this->update_size(); + if ( is_wp_error( $result ) ) { + return $result; + } + + return true; + } + /** * Flips current image. * From a71e9dbd7f71e0a5381e05471d533a1e784a8cb4 Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Fri, 25 Sep 2026 17:38:57 -0600 Subject: [PATCH 38/84] Vips: Add _resize() and make_subsize() --- .../class-wp-image-editor-vips.php | 103 ++++++++++++++++-- tests/phpunit/tests/image/editorVips.php | 70 ++++++++++++ 2 files changed, 162 insertions(+), 11 deletions(-) diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index 713cd85497d14..34fdf0387f130 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -297,29 +297,56 @@ public function resize( $max_w, $max_h, $crop = false ) { return true; } + $image = $this->_resize( $max_w, $max_h, $crop ); + + if ( is_wp_error( $image ) ) { + return $image; + } + + $this->image = $image; + + return true; + } + + /** + * Resizes the image and returns it, leaving `$this->image` alone. + * + * `$this->size` is updated to the destination dimensions because the save + * methods report the image size from there. Callers that need the previous + * dimensions back are expected to restore them. + * + * @since 7.2.0 + * + * @param int|null $max_w Image width. + * @param int|null $max_h Image height. + * @param bool|array $crop Optional. Image cropping behavior. Default false. + * @return Jcupitt\Vips\Image|WP_Error Resized image, or WP_Error on failure. + */ + protected function _resize( $max_w, $max_h, $crop = false ) { $dims = image_resize_dimensions( $this->size['width'], $this->size['height'], $max_w, $max_h, $crop ); if ( ! $dims ) { - return new WP_Error( 'error_getting_dimensions', __( 'Could not calculate resized image dimensions' ) ); + return new WP_Error( 'error_getting_dimensions', __( 'Could not calculate resized image dimensions' ), $this->file ); } list( $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h ) = $dims; - if ( $crop ) { - return $this->crop( $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h ); - } - try { - // Use resize instead of thumbnail_image for more control. - // Calculate scale factor. - $h_scale = $dst_w / $this->size['width']; - $v_scale = $dst_h / $this->size['height']; + $image = $this->image; + + // Crop to the source region first, when it is smaller than the whole image. + if ( (int) $src_w !== $this->size['width'] || (int) $src_h !== $this->size['height'] ) { + $image = $image->crop( (int) $src_x, (int) $src_y, (int) $src_w, (int) $src_h ); + } - $this->image = $this->image->resize( $h_scale, array( 'vscale' => $v_scale ) ); + // Then scale that region to the destination dimensions. + if ( (int) $src_w !== $dst_w || (int) $src_h !== $dst_h ) { + $image = $image->resize( $dst_w / (int) $src_w, array( 'vscale' => $dst_h / (int) $src_h ) ); + } $this->update_size( $dst_w, $dst_h ); $this->resized = true; - return true; + return $image; } catch ( Exception $e ) { return new WP_Error( 'image_resize_error', $e->getMessage() ); } @@ -402,6 +429,60 @@ public function multi_resize( $sizes ) { return $metadata; } + /** + * Creates an image sub-size and returns the image meta data value for it. + * + * @since 7.2.0 + * + * @param array $size_data { + * Array of size data. + * + * @type int $width The maximum width in pixels. + * @type int $height The maximum height in pixels. + * @type bool|array $crop Whether to crop the image to exact dimensions. + * } + * @return array|WP_Error The image data array for inclusion in the `sizes` array in the image meta, + * WP_Error object on error. + */ + public function make_subsize( $size_data ) { + if ( ! isset( $size_data['width'] ) && ! isset( $size_data['height'] ) ) { + return new WP_Error( 'image_subsize_create_error', __( 'Cannot resize the image. Both width and height are not set.' ) ); + } + + $orig_size = $this->size; + $orig_image = $this->image; + + $size_data['width'] = isset( $size_data['width'] ) ? $size_data['width'] : null; + $size_data['height'] = isset( $size_data['height'] ) ? $size_data['height'] : null; + $size_data['crop'] = isset( $size_data['crop'] ) ? $size_data['crop'] : false; + + if ( ( $orig_size['width'] === $size_data['width'] ) && ( $orig_size['height'] === $size_data['height'] ) ) { + return new WP_Error( 'image_subsize_create_error', __( 'The image already has the requested size.' ) ); + } + + $resized = $this->_resize( $size_data['width'], $size_data['height'], $size_data['crop'] ); + + if ( is_wp_error( $resized ) ) { + $this->image = $orig_image; + $this->size = $orig_size; + + return $resized; + } + + $saved = $this->_save( $resized ); + + // The editor keeps the image it was loaded with, so further sub-sizes are all + // derived from the same original rather than from the previous sub-size. + $this->image = $orig_image; + $this->size = $orig_size; + + if ( ! is_wp_error( $saved ) ) { + unset( $saved['path'] ); + } + + return $saved; + } + /** * Crops Image. * diff --git a/tests/phpunit/tests/image/editorVips.php b/tests/phpunit/tests/image/editorVips.php index a520a1dc811c2..10f782d74053a 100644 --- a/tests/phpunit/tests/image/editorVips.php +++ b/tests/phpunit/tests/image/editorVips.php @@ -110,6 +110,76 @@ public function test_single_multi_resize() { ); } + /** + * Tests that make_subsize() creates a size and leaves the editor as it was. + * + * `_wp_make_subsizes()` prefers `make_subsize()` over `multi_resize()`, so each + * sub-size has to be derived from the loaded image and the editor has to keep + * its original dimensions for the next call. + */ + public function test_make_subsize() { + $file = DIR_TESTDATA . '/images/waffles.jpg'; + + $vips_image_editor = new WP_Image_Editor_Vips( $file ); + $vips_image_editor->load(); + + $original_size = $vips_image_editor->get_size(); + + $scaled = $vips_image_editor->make_subsize( + array( + 'width' => (int) round( $original_size['width'] / 2 ), + 'height' => (int) round( $original_size['height'] / 2 ), + ) + ); + $this->assertNotWPError( $scaled ); + + $cropped = $vips_image_editor->make_subsize( + array( + 'width' => 100, + 'height' => 100, + 'crop' => true, + ) + ); + $this->assertNotWPError( $cropped ); + + // Matches multi_resize(): no path, and the metadata describes the real file. + $this->assertArrayNotHasKey( 'path', $scaled ); + $this->assertArrayNotHasKey( 'path', $cropped ); + + $this->assertImageDimensions( + DIR_TESTDATA . '/images/' . $scaled['file'], + $scaled['width'], + $scaled['height'] + ); + $this->assertImageDimensions( + DIR_TESTDATA . '/images/' . $cropped['file'], + $cropped['width'], + $cropped['height'] + ); + + // A cropped sub-size is exactly the requested dimensions. + $this->assertSame( 100, $cropped['width'] ); + $this->assertSame( 100, $cropped['height'] ); + + // The second sub-size came from the loaded image, not from the first one. + $this->assertSame( $original_size, $vips_image_editor->get_size() ); + } + + /** + * Tests that make_subsize() refuses a size that the image already has. + */ + public function test_make_subsize_does_not_duplicate_the_original_size() { + $file = DIR_TESTDATA . '/images/waffles.jpg'; + + $vips_image_editor = new WP_Image_Editor_Vips( $file ); + $vips_image_editor->load(); + + $result = $vips_image_editor->make_subsize( $vips_image_editor->get_size() ); + + $this->assertWPError( $result ); + $this->assertSame( 'image_subsize_create_error', $result->get_error_code() ); + } + /** * Tests that multi_resize() does not create an image when dimensions are missing. * From c730360f05eeb8620f2fc95266609b307d859d65 Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Fri, 25 Sep 2026 17:43:46 -0600 Subject: [PATCH 39/84] Tests: Cover EXIF orientation removal on rotate for Vips --- tests/phpunit/tests/image/editorVips.php | 33 ++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/tests/phpunit/tests/image/editorVips.php b/tests/phpunit/tests/image/editorVips.php index 10f782d74053a..b77206401760a 100644 --- a/tests/phpunit/tests/image/editorVips.php +++ b/tests/phpunit/tests/image/editorVips.php @@ -641,6 +641,39 @@ public function test_rotate() { ); } + /** + * Tests resetting Exif orientation data on rotate. + * + * @ticket 37140 + * @requires function exif_read_data + */ + public function test_remove_orientation_data_on_rotate() { + $file = DIR_TESTDATA . '/images/test-image-upside-down.jpg'; + $data = wp_read_image_metadata( $file ); + + // The orientation value 3 is equivalent to rotated upside down (180 degrees). + $this->assertSame( 3, (int) $data['orientation'], 'Orientation value read from does not match image file Exif data: ' . $file ); + + $vips_image_editor = new WP_Image_Editor_Vips( $file ); + $vips_image_editor->load(); + + // Test a value that would not lead back to 1, as WP is resetting the value to 1 manually. + $vips_image_editor->rotate( 90 ); + + $temp_tmp = tempnam( get_temp_dir(), 'vips_rotate_' ); + $temp_file = $temp_tmp . '.jpg'; + $saved = $vips_image_editor->save( $temp_file, 'image/jpeg' ); + $this->assertNotWPError( $saved ); + + $data = wp_read_image_metadata( $saved['path'] ); + + unlink( $temp_tmp ); + unlink( $saved['path'] ); + + // Make sure the image is no longer in The Upside Down Exif orientation. + $this->assertSame( 1, (int) $data['orientation'], 'Orientation Exif data was not updated after rotating image: ' . $file ); + } + /** * Tests that flipping along the horizontal axis mirrors the image vertically. */ From e4f89435ba4701896c917c5a0c7add82d7d1606b Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Fri, 25 Sep 2026 17:46:53 -0600 Subject: [PATCH 40/84] Vips: Reset the EXIF orientation when rotating or flipping --- .../class-wp-image-editor-vips.php | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index 34fdf0387f130..56278b1f00473 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -568,6 +568,10 @@ public function rotate( $angle ) { $this->image = $this->image->rotate( $angle ); } + // The pixels no longer match the EXIF orientation tag, and a stale tag + // orients the saved file a second time when it is loaded again. + $this->reset_exif_orientation(); + // Update size since rotation may change dimensions. $result = $this->update_size(); if ( is_wp_error( $result ) ) { @@ -652,12 +656,34 @@ public function flip( $horz, $vert ) { $this->image = $this->image->flipver(); } + // Flipping leaves the tag describing the unflipped pixels. + $this->reset_exif_orientation(); + return true; } catch ( Exception $e ) { return new WP_Error( 'image_flip_error', $e->getMessage() ); } } + /** + * Resets the EXIF orientation tag after the pixels have been transformed. + * + * The tag describes the original pixels, so leaving it in place orients the saved + * file a second time when it is loaded again. This is the equivalent of the Imagick + * editor resetting the tag with `setImageOrientation()`. + * + * libvips writes JPEG EXIF from the EXIF block rather than from the orientation + * field, so setting the field on its own never reaches the file. `autorot()` is the + * operation that rewrites the block. Declaring the image upright first means it has + * nothing to apply, which leaves the pixels alone and only corrects the tag. + * + * @since 7.2.0 + */ + protected function reset_exif_orientation() { + $this->image->set( 'orientation', 1 ); + $this->image = $this->image->autorot(); + } + /** * Saves current image to file. * From 7f6d75553eccf09fcd44540cd8037dbb95f95e66 Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Fri, 25 Sep 2026 17:49:09 -0600 Subject: [PATCH 41/84] Tests: Cover directory creation when saving for Vips --- tests/phpunit/tests/image/editorVips.php | 28 ++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/tests/phpunit/tests/image/editorVips.php b/tests/phpunit/tests/image/editorVips.php index b77206401760a..d5cab95a4116b 100644 --- a/tests/phpunit/tests/image/editorVips.php +++ b/tests/phpunit/tests/image/editorVips.php @@ -732,6 +732,34 @@ public function test_image_non_existent_extension() { $this->assertTrue( $loaded ); } + /** + * Tests that saving creates the destination directory when it is missing. + * + * libvips does not create directories for the file it writes, so the editor has to + * do that itself before writing. + */ + public function test_directory_creation() { + $file = realpath( DIR_TESTDATA ) . '/images/a2-small.jpg'; + $directory = realpath( DIR_TESTDATA ) . '/images/nonexistent-directory'; + + $vips_image_editor = new WP_Image_Editor_Vips( $file ); + + $this->assertFileDoesNotExist( $directory ); + + $loaded = $vips_image_editor->load(); + $this->assertNotWPError( $loaded ); + + $resized = $vips_image_editor->resize( 100, 100, true ); + $this->assertNotWPError( $resized ); + + $saved = $vips_image_editor->save( $directory . '/a2-small-cropped.jpg' ); + + unlink( $directory . '/a2-small-cropped.jpg' ); + rmdir( $directory ); + + $this->assertNotWPError( $saved ); + } + /** * Tests that images can be loaded and written over streams. */ From 22fa83161c93d152563276f6df75ea2769a55a1d Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Fri, 25 Sep 2026 17:51:28 -0600 Subject: [PATCH 42/84] Tests: Cover 16-bit and palette images for Vips --- tests/phpunit/tests/image/editorVips.php | 128 +++++++++++++++++++++++ 1 file changed, 128 insertions(+) diff --git a/tests/phpunit/tests/image/editorVips.php b/tests/phpunit/tests/image/editorVips.php index d5cab95a4116b..78153db4ba094 100644 --- a/tests/phpunit/tests/image/editorVips.php +++ b/tests/phpunit/tests/image/editorVips.php @@ -960,4 +960,132 @@ public function test_repeated_reads_from_one_instance() { unlink( $first_file ); unlink( $second_file ); } + + /** + * Reads the PNG colour type out of the IHDR chunk. + * + * @param string $file Path to a PNG file. + * @return int The colour type: 0 grayscale, 2 RGB, 3 palette, 4 grayscale with alpha, 6 RGBA. + */ + private function get_png_color_type( $file ) { + // The colour type is the 10th byte of the IHDR chunk, at offset 25 of the file. + return ord( file_get_contents( $file, false, null, 25, 1 ) ); + } + + /** + * Tests that alpha transparency survives a resize. + * + * @ticket 63448 + * + * @dataProvider data_alpha_transparency_is_preserved_after_resize + * + * @param string $file_path Path to the image file. + */ + public function test_alpha_transparency_is_preserved_after_resize( $file_path ) { + $temp_tmp = tempnam( get_temp_dir(), 'vips_alpha_' ); + $temp_file = $temp_tmp . '.png'; + + $vips_image_editor = new WP_Image_Editor_Vips( $file_path ); + $vips_image_editor->load(); + + $size = $vips_image_editor->get_size(); + $this->assertNotWPError( $vips_image_editor->resize( $size['width'] * 0.5, $size['height'] * 0.5 ) ); + + $saved = $vips_image_editor->save( $temp_file ); + $this->assertNotWPError( $saved ); + + $color_type = $this->get_png_color_type( $saved['path'] ); + + unlink( $temp_tmp ); + unlink( $saved['path'] ); + + $this->assertContains( $color_type, array( 4, 6 ), "Alpha transparency should be preserved after resize for {$file_path}." ); + } + + /** + * Data provider for test_alpha_transparency_is_preserved_after_resize. + * + * @return array[] + */ + public static function data_alpha_transparency_is_preserved_after_resize() { + return array( + 'oval-or8' => array( + DIR_TESTDATA . '/images/png-tests/oval-or8.png', + ), + 'oval-or8-grayscale-indexed' => array( + DIR_TESTDATA . '/images/png-tests/oval-or8-grayscale-indexed.png', + ), + ); + } + + /** + * Tests that the PNG colour type is preserved after resizing. + * + * The colour type is read straight from the IHDR chunk, which is the same thing the + * Imagick editor exposes as the `png:IHDR.color-type-orig` property. An indexed PNG + * that comes back as true colour takes far more space than the original. + * + * @ticket 63448 + * + * @dataProvider data_png_color_type_after_resize + * + * @param string $file_path Path to the image file. + * @param int $expected_color_type The expected original colour type. + */ + public function test_png_color_type_is_preserved_after_resize( $file_path, $expected_color_type ) { + $temp_tmp = tempnam( get_temp_dir(), 'vips_colortype_' ); + $temp_file = $temp_tmp . '.png'; + + $this->assertSame( + $expected_color_type, + $this->get_png_color_type( $file_path ), + "The fixture itself is not colour type {$expected_color_type}: {$file_path}." + ); + + $vips_image_editor = new WP_Image_Editor_Vips( $file_path ); + $vips_image_editor->load(); + + $size = $vips_image_editor->get_size(); + $this->assertNotWPError( $vips_image_editor->resize( $size['width'] * 0.5, $size['height'] * 0.5 ) ); + + $saved = $vips_image_editor->save( $temp_file ); + $this->assertNotWPError( $saved ); + + $color_type = $this->get_png_color_type( $saved['path'] ); + + unlink( $temp_tmp ); + unlink( $saved['path'] ); + + $this->assertSame( + $expected_color_type, + $color_type, + "The PNG colour type should be preserved after resize for {$file_path}." + ); + } + + /** + * Data provider for test_png_color_type_is_preserved_after_resize. + * + * @return array[] + */ + public static function data_png_color_type_after_resize() { + return array( + 'vivid-green-bird_color_type_6' => array( + DIR_TESTDATA . '/images/png-tests/vivid-green-bird.png', + 6, // RGBA. + ), + 'grayscale-test-image_color_type_4' => array( + DIR_TESTDATA . '/images/png-tests/grayscale-test-image.png', + 4, // Grayscale with Alpha. + ), + 'rabbit-time-paletted-or8_color_type_3' => array( + DIR_TESTDATA . '/images/png-tests/rabbit-time-paletted-or8.png', + 3, // Paletted. + ), + 'test8_color_type_3' => array( + DIR_TESTDATA . '/images/png-tests/test8.png', + 3, // Paletted. + ), + ); + } } From 45d17b9f33dbe13647c1bf812bdde20a11423677 Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Fri, 25 Sep 2026 17:54:30 -0600 Subject: [PATCH 43/84] Vips: Keep paletted PNGs paletted when saving --- .../class-wp-image-editor-vips.php | 25 +++++++++++++++++++ tests/phpunit/tests/image/editorVips.php | 7 +++++- 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index 56278b1f00473..5979e0b9791a2 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -54,6 +54,16 @@ class WP_Image_Editor_Vips extends WP_Image_Editor { */ protected $lossless = false; + /** + * Whether the loaded image is a paletted PNG. + * + * libvips expands the palette on load, so the original colour type has to be read + * from the file in order to ask for a palette back when saving. + * + * @var bool + */ + protected $paletted = false; + /** * Cache of mime type support checks. * @@ -212,6 +222,14 @@ public function load() { $this->mime_type = $this->default_mime_type; } + // PNG colour type 3 is an indexed palette. See the property for why it is read + // from the file rather than from the loaded image. + if ( 'image/png' === $this->mime_type ) { + $ihdr = @file_get_contents( $this->file, false, null, 25, 1 ); + + $this->paletted = ( false !== $ihdr && 3 === ord( $ihdr ) ); + } + $this->update_size( $width, $height ); $this->original_image = $this->image->copy(); @@ -755,6 +773,13 @@ protected function _save( $image, $filename = null, $mime_type = null ) { $compression = 9 - round( ( $quality / 100 ) * 9 ); $save_options['compression'] = max( 0, min( 9, $compression ) ); $save_options['strip'] = $strip_meta; + + // Asking for a palette back keeps an indexed PNG indexed. Without it the + // resized image is written as true colour, which is much larger than the + // file it came from. The option requires libvips 8.13. + if ( $this->paletted && version_compare( Jcupitt\Vips\Config::version(), '8.13', '>=' ) ) { + $save_options['palette'] = true; + } break; case 'image/webp': diff --git a/tests/phpunit/tests/image/editorVips.php b/tests/phpunit/tests/image/editorVips.php index 78153db4ba094..4e783c81440e3 100644 --- a/tests/phpunit/tests/image/editorVips.php +++ b/tests/phpunit/tests/image/editorVips.php @@ -996,10 +996,15 @@ public function test_alpha_transparency_is_preserved_after_resize( $file_path ) $color_type = $this->get_png_color_type( $saved['path'] ); + // Colour types 4 and 6 have an alpha channel of their own. Colour type 3 keeps its + // alpha in a tRNS chunk. + $chunks = file_get_contents( $saved['path'], false, null, 8 ); + $has_alpha = in_array( $color_type, array( 4, 6 ), true ) || false !== strpos( $chunks, 'tRNS' ); + unlink( $temp_tmp ); unlink( $saved['path'] ); - $this->assertContains( $color_type, array( 4, 6 ), "Alpha transparency should be preserved after resize for {$file_path}." ); + $this->assertTrue( $has_alpha, "Alpha transparency should be preserved after resize for {$file_path}." ); } /** From 7acdd1b3cdf1f1843f3385d2c7aea3eb31af5014 Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Fri, 25 Sep 2026 18:10:43 -0600 Subject: [PATCH 44/84] Vips: Build multi_resize on make_subsize --- .../class-wp-image-editor-vips.php | 63 ++----------------- 1 file changed, 4 insertions(+), 59 deletions(-) diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index 5979e0b9791a2..fbd08df4fdb6b 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -30,13 +30,6 @@ class WP_Image_Editor_Vips extends WP_Image_Editor { */ protected $image; - /** - * Original image object used for multi_resize operations. - * - * @var Jcupitt\Vips\Image|null - */ - protected $original_image; - /** * Whether the image has been resized or cropped since it was loaded. * @@ -231,7 +224,6 @@ public function load() { } $this->update_size( $width, $height ); - $this->original_image = $this->image->copy(); return $this->set_quality(); } catch ( Exception $e ) { @@ -387,61 +379,14 @@ protected function _resize( $max_w, $max_h, $crop = false ) { * @return array An array of resized images metadata by size. */ public function multi_resize( $sizes ) { - $metadata = array(); - $orig_size = $this->size; - - if ( ! $this->original_image ) { - try { - $this->original_image = $this->image->copy(); - } catch ( Exception $e ) { - return $metadata; - } - } + $metadata = array(); foreach ( $sizes as $size => $size_data ) { - try { - $this->image = $this->original_image->copy(); - } catch ( Exception $e ) { - continue; - } - - $this->size = $orig_size; - - if ( ! isset( $size_data['width'] ) && ! isset( $size_data['height'] ) ) { - continue; - } - - if ( ! isset( $size_data['width'] ) ) { - $size_data['width'] = null; - } + $meta = $this->make_subsize( $size_data ); - if ( ! isset( $size_data['height'] ) ) { - $size_data['height'] = null; + if ( ! is_wp_error( $meta ) ) { + $metadata[ $size ] = $meta; } - - if ( ! isset( $size_data['crop'] ) ) { - $size_data['crop'] = false; - } - - $resize_result = $this->resize( $size_data['width'], $size_data['height'], $size_data['crop'] ); - $duplicate = ( ( $orig_size['width'] === $size_data['width'] ) && ( $orig_size['height'] === $size_data['height'] ) ); - - if ( ! is_wp_error( $resize_result ) && ! $duplicate ) { - $resized = $this->_save( $this->image ); - - if ( ! is_wp_error( $resized ) && $resized ) { - unset( $resized['path'] ); - $metadata[ $size ] = $resized; - } - } - } - - // Restore original image and dimensions. - try { - $this->image = $this->original_image->copy(); - $this->size = $orig_size; - } catch ( Exception $e ) { - $this->size = $orig_size; } return $metadata; From f9b1747680c3f8ebce754241dbb41b296c6fd542 Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Fri, 25 Sep 2026 18:42:52 -0600 Subject: [PATCH 45/84] Vips: Compress PNGs like the Imagick editor --- src/wp-includes/class-wp-image-editor-vips.php | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index fbd08df4fdb6b..a5c065f9ad1ab 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -712,11 +712,10 @@ protected function _save( $image, $filename = null, $mime_type = null ) { break; case 'image/png': - // PNG quality in VIPS is compression level (0-9). - // Convert WP quality (0-100) to VIPS compression (9-0). - $quality = $this->get_quality(); - $compression = 9 - round( ( $quality / 100 ) * 9 ); - $save_options['compression'] = max( 0, min( 9, $compression ) ); + // PNG is lossless, so there is no quality to trade away, and the Imagick + // editor saves at maximum deflate compression. Deriving a level from the + // quality instead wrote files far larger than the source they came from. + $save_options['compression'] = 9; $save_options['strip'] = $strip_meta; // Asking for a palette back keeps an indexed PNG indexed. Without it the @@ -817,9 +816,8 @@ public function stream( $mime_type = null ) { switch ( $mime_type ) { case 'image/png': - $quality = $this->get_quality(); - $compression = 9 - round( ( $quality / 100 ) * 9 ); - $save_options['compression'] = max( 0, min( 9, $compression ) ); + // PNG is lossless; see the note in _save(). + $save_options['compression'] = 9; break; case 'image/webp': From 0bbef644c4e68a3bbb4a9d11f3bec43e38febb16 Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Fri, 25 Sep 2026 18:44:45 -0600 Subject: [PATCH 46/84] Vips: Honour the image_max_bit_depth filter --- .../class-wp-image-editor-imagick.php | 5 +- .../class-wp-image-editor-vips.php | 78 +++++++++++++++++++ tests/phpunit/tests/image/editorVips.php | 60 ++++++++++++++ 3 files changed, 141 insertions(+), 2 deletions(-) diff --git a/src/wp-includes/class-wp-image-editor-imagick.php b/src/wp-includes/class-wp-image-editor-imagick.php index f3dd8e9fff06c..b26958cd383a8 100644 --- a/src/wp-includes/class-wp-image-editor-imagick.php +++ b/src/wp-includes/class-wp-image-editor-imagick.php @@ -790,8 +790,9 @@ protected function thumbnail_image( $dst_w, $dst_h, $filter_name = 'FILTER_TRIAN /** * Filters the maximum bit depth of resized images. * - * This filter only applies when resizing using the Imagick editor since GD - * does not support getting or setting bit depth. + * This filter applies when resizing using the Imagick or VIPS editors. GD does + * not support getting or setting bit depth, and VIPS can only honour it for the + * encoders that accept a bit depth. * * Use this to adjust the maximum bit depth of resized images. * diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index a5c065f9ad1ab..3f232733bd39c 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -647,6 +647,76 @@ protected function reset_exif_orientation() { $this->image = $this->image->autorot(); } + /** + * Returns the bit depth that a libvips band format stores. + * + * @since 7.2.0 + * + * @param string $format A libvips band format, such as `uchar` or `ushort`. + * @return int The bit depth of that format. + */ + protected static function get_format_bit_depth( $format ) { + switch ( $format ) { + case 'ushort': + case 'short': + return 16; + case 'uint': + case 'int': + case 'float': + return 32; + case 'double': + case 'complex': + return 64; + case 'dpcomplex': + return 128; + default: + return 8; + } + } + + /** + * Returns the bit depth to save an image at, honouring `image_max_bit_depth`. + * + * libvips stores samples in a fixed set of band formats rather than at an arbitrary + * bit depth, and only some encoders accept a bit depth at all. This picks the nearest + * depth the encoder offers and returns null for everything else, which leaves the + * image at its own depth. + * + * @since 7.2.0 + * + * @param Jcupitt\Vips\Image $image The image being saved. + * @param string $mime_type The mime type it is being saved as. + * @return int|null The bit depth to save at, or null to leave it unchanged. + */ + protected function get_save_bit_depth( $image, $mime_type ) { + $image_depth = self::get_format_bit_depth( $image->format ); + + /** This filter is documented in wp-includes/class-wp-image-editor-imagick.php */ + $max_depth = apply_filters( 'image_max_bit_depth', $image_depth, $image_depth ); + + if ( $max_depth >= $image_depth ) { + return null; + } + + switch ( $mime_type ) { + case 'image/png': + // pngsave writes 8 or 16 bits per sample. + return $max_depth <= 8 ? 8 : null; + + case 'image/avif': + case 'image/heic': + case 'image/heif': + // heifsave accepts 8, 10 or 12 bits per sample. + if ( $max_depth <= 8 ) { + return 8; + } + + return $max_depth <= 10 ? 10 : 12; + } + + return null; + } + /** * Saves current image to file. * @@ -745,6 +815,14 @@ protected function _save( $image, $filename = null, $mime_type = null ) { break; } + // Of the formats above, only PNG and the HEIF family can be asked to store + // fewer bits per sample. + $bit_depth = $this->get_save_bit_depth( $image, $mime_type ); + + if ( null !== $bit_depth ) { + $save_options['bitdepth'] = $bit_depth; + } + if ( wp_is_stream( $filename ) ) { $buffer = $image->writeToBuffer( '.' . $extension, $save_options ); if ( false === file_put_contents( $filename, $buffer ) ) { diff --git a/tests/phpunit/tests/image/editorVips.php b/tests/phpunit/tests/image/editorVips.php index 4e783c81440e3..fea4d93a98a46 100644 --- a/tests/phpunit/tests/image/editorVips.php +++ b/tests/phpunit/tests/image/editorVips.php @@ -1093,4 +1093,64 @@ public static function data_png_color_type_after_resize() { ), ); } + + /** + * Reads the PNG bit depth out of the IHDR chunk. + * + * @param string $file Path to a PNG file. + * @return int The bit depth per sample. + */ + private function get_png_bit_depth( $file ) { + // The bit depth is the 9th byte of the IHDR chunk, at offset 24 of the file. + return ord( file_get_contents( $file, false, null, 24, 1 ) ); + } + + /** + * Tests that the image_max_bit_depth filter limits the saved bit depth. + * + * The source is a 10 bit AVIF that libvips holds in 16 bit samples. It is saved as + * a PNG because that is one of the two encoders here that can be asked to store + * fewer bits per sample. + * + * @ticket 62285 + */ + public function test_image_max_bit_depth() { + $file = DIR_TESTDATA . '/images/colors_hdr_p3.avif'; + + if ( ! WP_Image_Editor_Vips::supports_mime_type( 'image/avif' ) ) { + $this->markTestSkipped( 'The image editor does not support the AVIF mime type.' ); + } + + $temp_tmp = tempnam( get_temp_dir(), 'vips_depth_' ); + $temp_file = $temp_tmp . '.png'; + + $vips_image_editor = new WP_Image_Editor_Vips( $file ); + $vips_image_editor->load(); + + $size = $vips_image_editor->get_size(); + $this->assertNotWPError( $vips_image_editor->resize( $size['width'] * 0.5, $size['height'] * 0.5 ) ); + + // Without the filter the image is saved at its own bit depth. + $saved = $vips_image_editor->save( $temp_file, 'image/png' ); + $this->assertNotWPError( $saved ); + $this->assertSame( 16, $this->get_png_bit_depth( $saved['path'] ), 'The bit depth should be kept when the filter does not limit it.' ); + + add_filter( + 'image_max_bit_depth', + static function () { + return 8; + } + ); + + $limited_editor = new WP_Image_Editor_Vips( $file ); + $limited_editor->load(); + $this->assertNotWPError( $limited_editor->resize( $size['width'] * 0.5, $size['height'] * 0.5 ) ); + + $limited = $limited_editor->save( $temp_file, 'image/png' ); + $this->assertNotWPError( $limited ); + $this->assertSame( 8, $this->get_png_bit_depth( $limited['path'] ), 'The filter should limit the saved bit depth.' ); + + unlink( $temp_tmp ); + unlink( $saved['path'] ); + } } From c4ced60c38b88f42bf2fdd2d3a445ad158c2984d Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Fri, 25 Sep 2026 18:48:16 -0600 Subject: [PATCH 47/84] Vips: Only read EXIF when the extension is available --- src/wp-includes/class-wp-image-editor-vips.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index 3f232733bd39c..8d3562dbba39f 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -558,7 +558,10 @@ public function rotate( $angle ) { public function maybe_exif_rotate() { $orientation = null; - if ( 'image/jpeg' === $this->mime_type ) { + // The exif extension is optional, so this is checked even though PHPStan reports + // it as always true in the environment it analyses. + // @phpstan-ignore function.alreadyNarrowedType (The exif extension is optional.) + if ( is_callable( 'exif_read_data' ) && 'image/jpeg' === $this->mime_type ) { $exif_data = @exif_read_data( $this->file ); if ( ! empty( $exif_data['Orientation'] ) ) { From a64084a10b92d614868a70e1d86f86c8b7696a3b Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Fri, 25 Sep 2026 19:25:19 -0600 Subject: [PATCH 48/84] Site Health: Describe VIPS as the preferred image editor --- src/wp-admin/includes/class-wp-site-health.php | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/src/wp-admin/includes/class-wp-site-health.php b/src/wp-admin/includes/class-wp-site-health.php index b9e95387f65e2..987a41b894b17 100644 --- a/src/wp-admin/includes/class-wp-site-health.php +++ b/src/wp-admin/includes/class-wp-site-health.php @@ -1032,10 +1032,14 @@ public function get_test_php_extensions() { 'required' => false, 'fallback_for' => 'zip', ), + /* + * VIPS is the preferred image editor when it is available, so its result is + * always reported rather than only being checked when another editor has + * already failed. It has no fallback itself because it is the first choice. + */ 'vips' => array( - 'extension' => 'ffi', - 'required' => false, - 'fallback_for' => 'imagick', + 'extension' => 'ffi', + 'required' => false, ), ); From ad2144f2d25f9e849a3d6806f0bda4a5f494a5fa Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Sat, 26 Sep 2026 07:20:12 -0600 Subject: [PATCH 49/84] Vips: Query the save suffixes before probing encoders --- .../class-wp-image-editor-vips.php | 111 ++++++++++++++++-- 1 file changed, 104 insertions(+), 7 deletions(-) diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index 8d3562dbba39f..9c39b4ba57685 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -60,13 +60,23 @@ class WP_Image_Editor_Vips extends WP_Image_Editor { /** * Cache of mime type support checks. * - * Dynamic writeToBuffer probe is used because VIPS support depends on runtime configuration - * and optional dependencies. Cache prevents repeated expensive encoder checks. + * VIPS support depends on runtime configuration and optional dependencies, so the + * answer has to be determined at runtime. Caching it avoids repeating the check. * * @var array */ protected static $mime_support_cache = array(); + /** + * Extensions libvips can save images to, including the leading dot. + * + * Null until it has been queried. An empty array means the query is unavailable on + * the loaded libvips, in which case callers fall back to probing an encoder. + * + * @var string[]|null + */ + protected static $save_suffixes; + /** * Checks to see if current environment supports VIPS. * @@ -147,6 +157,43 @@ public static function supports_mime_type( $mime_type ) { $target_extension = isset( $extension_map[ $vips_extension ] ) ? $extension_map[ $vips_extension ] : strtolower( $vips_extension ); + $supported = self::can_save_extension( $target_extension ); + + self::$mime_support_cache[ $mime_type ] = $supported; + + return $supported; + } + + /** + * Checks whether libvips can save images with the given extension. + * + * The list of save suffixes is one query covering every format the build supports, + * which is the closest equivalent of `Imagick::queryFormats()`. It is asked first + * because it is around a hundred times cheaper than encoding. + * + * That list describes what libvips was built with, so it is not sufficient on its + * own. libheif loads its encoders as plugins at runtime, which means a build that + * lists HEIF support can still fail to encode when no encoder plugin is installed. + * The formats that resolve their encoder that way are always verified by encoding, + * as is anything the list does not mention at all. + * + * @since 7.2.0 + * + * @param string $extension A libvips suffix without the leading dot, for example `jpg`. + * @return bool Whether the extension can be saved. + */ + protected static function can_save_extension( $extension ) { + // Encoders that libvips reaches through a runtime plugin loader rather than by + // linking them directly. Their presence in the suffix list says nothing about + // whether the plugin needed to encode is installed. + $runtime_encoder_formats = array( 'heic', 'heif', 'avif' ); + + if ( ! in_array( $extension, $runtime_encoder_formats, true ) + && in_array( '.' . $extension, self::get_save_suffixes(), true ) + ) { + return true; + } + // Probe encoder support directly. // Use Image::black() to test write support (encoding) rather than findLoad() which only tests read support (decoding). try { @@ -154,16 +201,66 @@ public static function supports_mime_type( $mime_type ) { // libvips picks the encoder from the suffix, so the buffer is given one. // Nothing is written to disk, so there is no temp file to clean up. - $buffer = $test_image->writeToBuffer( '.' . $target_extension ); + $buffer = $test_image->writeToBuffer( '.' . $extension ); - $supported = ! empty( $buffer ); + return ! empty( $buffer ); } catch ( Exception $e ) { - $supported = false; + return false; } + } - self::$mime_support_cache[ $mime_type ] = $supported; + /** + * Returns the extensions libvips can save images to. + * + * The result is cached because it is a property of the loaded libvips build rather + * than of any particular image. + * + * @since 7.2.0 + * + * @return string[] Extensions including the leading dot, or an empty array when the + * list cannot be determined and callers should probe instead. + */ + protected static function get_save_suffixes() { + if ( ! isset( self::$save_suffixes ) ) { + self::$save_suffixes = self::query_save_suffixes(); + } - return $supported; + return self::$save_suffixes; + } + + /** + * Asks libvips which save suffixes it supports. + * + * `vips_foreign_get_suffixes()` arrived in libvips 8.8 and is not declared to FFI by + * earlier bindings, so it is only called when the loaded version provides it. + * + * @since 7.2.0 + * + * @return string[] Extensions including the leading dot, or an empty array. + */ + protected static function query_save_suffixes() { + try { + if ( version_compare( Jcupitt\Vips\Config::version(), '8.8', '<' ) ) { + return array(); + } + + // The returned list is NULL-terminated and owned by the caller. These two + // functions are declared to libvips, not to PHP, so PHPStan cannot see them. + // @phpstan-ignore method.notFound (Declared in the libvips FFI cdef.) + $all = Jcupitt\Vips\FFI::vips()->vips_foreign_get_suffixes(); + $suffixes = array(); + + for ( $i = 0; null !== $all[ $i ]; $i++ ) { + $suffixes[] = strtolower( \FFI::string( $all[ $i ] ) ); + } + + // @phpstan-ignore method.notFound (Declared in the glib FFI cdef.) + Jcupitt\Vips\FFI::glib()->g_strfreev( $all ); + + return array_values( array_unique( $suffixes ) ); + } catch ( Exception $e ) { + return array(); + } } /** From 2d3b1d24cd203a3cfd771b6edef0aa87961c59a7 Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Sat, 26 Sep 2026 07:40:06 -0600 Subject: [PATCH 50/84] Vips: Fold the mime support helpers together --- .../class-wp-image-editor-vips.php | 146 +++++++----------- 1 file changed, 59 insertions(+), 87 deletions(-) diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index 9c39b4ba57685..5e255f0ba8e43 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -129,13 +129,7 @@ public static function supports_mime_type( $mime_type ) { $vips_extension = strtoupper( self::get_extension( $mime_type ) ); - if ( ! $vips_extension ) { - self::$mime_support_cache[ $mime_type ] = false; - - return false; - } - - if ( ! self::test() ) { + if ( ! $vips_extension || ! self::test() ) { self::$mime_support_cache[ $mime_type ] = false; return false; @@ -155,112 +149,90 @@ public static function supports_mime_type( $mime_type ) { 'JXL' => 'jxl', ); - $target_extension = isset( $extension_map[ $vips_extension ] ) ? $extension_map[ $vips_extension ] : strtolower( $vips_extension ); - - $supported = self::can_save_extension( $target_extension ); + $extension = isset( $extension_map[ $vips_extension ] ) ? $extension_map[ $vips_extension ] : strtolower( $vips_extension ); - self::$mime_support_cache[ $mime_type ] = $supported; - - return $supported; - } - - /** - * Checks whether libvips can save images with the given extension. - * - * The list of save suffixes is one query covering every format the build supports, - * which is the closest equivalent of `Imagick::queryFormats()`. It is asked first - * because it is around a hundred times cheaper than encoding. - * - * That list describes what libvips was built with, so it is not sufficient on its - * own. libheif loads its encoders as plugins at runtime, which means a build that - * lists HEIF support can still fail to encode when no encoder plugin is installed. - * The formats that resolve their encoder that way are always verified by encoding, - * as is anything the list does not mention at all. - * - * @since 7.2.0 - * - * @param string $extension A libvips suffix without the leading dot, for example `jpg`. - * @return bool Whether the extension can be saved. - */ - protected static function can_save_extension( $extension ) { - // Encoders that libvips reaches through a runtime plugin loader rather than by - // linking them directly. Their presence in the suffix list says nothing about - // whether the plugin needed to encode is installed. + /* + * The list of save suffixes is one query covering every format libvips was built + * with, and is the closest equivalent of `Imagick::queryFormats()`. It is asked + * first because it is around a hundred times cheaper than encoding. + * + * It cannot be trusted on its own. libheif loads its encoders as plugins at + * runtime, so a build that lists HEIF support can still fail to encode when no + * encoder plugin is installed. Formats whose encoder resolves that way, and + * anything the list does not mention at all, are verified by encoding instead. + */ $runtime_encoder_formats = array( 'heic', 'heif', 'avif' ); - if ( ! in_array( $extension, $runtime_encoder_formats, true ) - && in_array( '.' . $extension, self::get_save_suffixes(), true ) - ) { - return true; + $supported = ! in_array( $extension, $runtime_encoder_formats, true ) + && in_array( '.' . $extension, self::get_save_suffixes(), true ); + + if ( ! $supported ) { + /* + * Probe encoder support directly. + * + * `Image::black()` tests writing (encoding), where `findLoad()` would only + * test reading (decoding). libvips picks the encoder from the suffix, and + * nothing reaches disk, so there is no temp file to clean up. + */ + try { + $test_image = Jcupitt\Vips\Image::black( 1, 1 ); + + $supported = ! empty( $test_image->writeToBuffer( '.' . $extension ) ); + } catch ( Exception $e ) { + $supported = false; + } } - // Probe encoder support directly. - // Use Image::black() to test write support (encoding) rather than findLoad() which only tests read support (decoding). - try { - $test_image = Jcupitt\Vips\Image::black( 1, 1 ); - - // libvips picks the encoder from the suffix, so the buffer is given one. - // Nothing is written to disk, so there is no temp file to clean up. - $buffer = $test_image->writeToBuffer( '.' . $extension ); + self::$mime_support_cache[ $mime_type ] = $supported; - return ! empty( $buffer ); - } catch ( Exception $e ) { - return false; - } + return $supported; } /** * Returns the extensions libvips can save images to. * - * The result is cached because it is a property of the loaded libvips build rather - * than of any particular image. + * This is a property of the loaded libvips build rather than of any particular image, + * so it is queried once and cached. + * + * `vips_foreign_get_suffixes()` is only declared to FFI when libvips 8.8 or later is + * loaded, so an older build reports an empty list and callers probe instead. * * @since 7.2.0 * * @return string[] Extensions including the leading dot, or an empty array when the - * list cannot be determined and callers should probe instead. + * list cannot be determined. */ protected static function get_save_suffixes() { - if ( ! isset( self::$save_suffixes ) ) { - self::$save_suffixes = self::query_save_suffixes(); + if ( isset( self::$save_suffixes ) ) { + return self::$save_suffixes; } - return self::$save_suffixes; - } + $suffixes = array(); - /** - * Asks libvips which save suffixes it supports. - * - * `vips_foreign_get_suffixes()` arrived in libvips 8.8 and is not declared to FFI by - * earlier bindings, so it is only called when the loaded version provides it. - * - * @since 7.2.0 - * - * @return string[] Extensions including the leading dot, or an empty array. - */ - protected static function query_save_suffixes() { try { - if ( version_compare( Jcupitt\Vips\Config::version(), '8.8', '<' ) ) { - return array(); - } + if ( version_compare( Jcupitt\Vips\Config::version(), '8.8', '>=' ) ) { + // The returned list is NULL-terminated and owned by the caller. These two + // functions are declared to libvips rather than to PHP, so PHPStan cannot + // see them. + // @phpstan-ignore method.notFound (Declared in the libvips FFI cdef.) + $all = Jcupitt\Vips\FFI::vips()->vips_foreign_get_suffixes(); + + for ( $i = 0; null !== $all[ $i ]; $i++ ) { + $suffixes[] = strtolower( \FFI::string( $all[ $i ] ) ); + } - // The returned list is NULL-terminated and owned by the caller. These two - // functions are declared to libvips, not to PHP, so PHPStan cannot see them. - // @phpstan-ignore method.notFound (Declared in the libvips FFI cdef.) - $all = Jcupitt\Vips\FFI::vips()->vips_foreign_get_suffixes(); - $suffixes = array(); + // @phpstan-ignore method.notFound (Declared in the glib FFI cdef.) + Jcupitt\Vips\FFI::glib()->g_strfreev( $all ); - for ( $i = 0; null !== $all[ $i ]; $i++ ) { - $suffixes[] = strtolower( \FFI::string( $all[ $i ] ) ); + $suffixes = array_values( array_unique( $suffixes ) ); } - - // @phpstan-ignore method.notFound (Declared in the glib FFI cdef.) - Jcupitt\Vips\FFI::glib()->g_strfreev( $all ); - - return array_values( array_unique( $suffixes ) ); } catch ( Exception $e ) { - return array(); + $suffixes = array(); } + + self::$save_suffixes = $suffixes; + + return $suffixes; } /** From 553a07a753ded80eff3a1c31e92bb95f60633b44 Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Sat, 26 Sep 2026 07:41:04 -0600 Subject: [PATCH 51/84] Vips: Stop listing JPEG XL as a supported format --- src/wp-includes/class-wp-image-editor-vips.php | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index 5e255f0ba8e43..a4d0c44225da5 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -135,6 +135,11 @@ public static function supports_mime_type( $mime_type ) { return false; } + /* + * WordPress registers no `image/jxl` mime type, so there is no entry for it here. + * The GD and Imagick editors report no support for it for the same reason, and + * `get_extension()` returns false before this map is consulted anyway. + */ $extension_map = array( 'JPEG' => 'jpg', 'JPG' => 'jpg', @@ -146,7 +151,6 @@ public static function supports_mime_type( $mime_type ) { 'HEIC' => 'heic', 'HEIF' => 'heif', 'AVIF' => 'avif', - 'JXL' => 'jxl', ); $extension = isset( $extension_map[ $vips_extension ] ) ? $extension_map[ $vips_extension ] : strtolower( $vips_extension ); From 405f35ec7c965277ab8a49e2067380aa7c4e655b Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Sat, 26 Sep 2026 07:49:38 -0600 Subject: [PATCH 52/84] Vips: Simplify the mime support check --- .../class-wp-image-editor-vips.php | 78 ++++--------------- 1 file changed, 17 insertions(+), 61 deletions(-) diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index a4d0c44225da5..8f7097d21a254 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -67,16 +67,6 @@ class WP_Image_Editor_Vips extends WP_Image_Editor { */ protected static $mime_support_cache = array(); - /** - * Extensions libvips can save images to, including the leading dot. - * - * Null until it has been queried. An empty array means the query is unavailable on - * the loaded libvips, in which case callers fall back to probing an encoder. - * - * @var string[]|null - */ - protected static $save_suffixes; - /** * Checks to see if current environment supports VIPS. * @@ -127,43 +117,20 @@ public static function supports_mime_type( $mime_type ) { return self::$mime_support_cache[ $mime_type ]; } - $vips_extension = strtoupper( self::get_extension( $mime_type ) ); + $extension = strtolower( self::get_extension( $mime_type ) ); - if ( ! $vips_extension || ! self::test() ) { + if ( ! $extension || ! self::test() ) { self::$mime_support_cache[ $mime_type ] = false; return false; } /* - * WordPress registers no `image/jxl` mime type, so there is no entry for it here. - * The GD and Imagick editors report no support for it for the same reason, and - * `get_extension()` returns false before this map is consulted anyway. - */ - $extension_map = array( - 'JPEG' => 'jpg', - 'JPG' => 'jpg', - 'PNG' => 'png', - 'WEBP' => 'webp', - 'GIF' => 'gif', - 'TIFF' => 'tif', - 'TIF' => 'tif', - 'HEIC' => 'heic', - 'HEIF' => 'heif', - 'AVIF' => 'avif', - ); - - $extension = isset( $extension_map[ $vips_extension ] ) ? $extension_map[ $vips_extension ] : strtolower( $vips_extension ); - - /* - * The list of save suffixes is one query covering every format libvips was built - * with, and is the closest equivalent of `Imagick::queryFormats()`. It is asked - * first because it is around a hundred times cheaper than encoding. - * - * It cannot be trusted on its own. libheif loads its encoders as plugins at - * runtime, so a build that lists HEIF support can still fail to encode when no - * encoder plugin is installed. Formats whose encoder resolves that way, and - * anything the list does not mention at all, are verified by encoding instead. + * The suffix list covers every format libvips was built with and is far cheaper + * than encoding, but it cannot be trusted alone: libheif loads its encoders as + * plugins at runtime, so a build that lists HEIF can still fail to encode when no + * encoder plugin is installed. Those formats, and anything the list omits, are + * verified by encoding instead. */ $runtime_encoder_formats = array( 'heic', 'heif', 'avif' ); @@ -171,13 +138,7 @@ public static function supports_mime_type( $mime_type ) { && in_array( '.' . $extension, self::get_save_suffixes(), true ); if ( ! $supported ) { - /* - * Probe encoder support directly. - * - * `Image::black()` tests writing (encoding), where `findLoad()` would only - * test reading (decoding). libvips picks the encoder from the suffix, and - * nothing reaches disk, so there is no temp file to clean up. - */ + // Encode a 1x1 image to test writing, where findLoad() tests only reading. try { $test_image = Jcupitt\Vips\Image::black( 1, 1 ); @@ -195,29 +156,26 @@ public static function supports_mime_type( $mime_type ) { /** * Returns the extensions libvips can save images to. * - * This is a property of the loaded libvips build rather than of any particular image, - * so it is queried once and cached. - * - * `vips_foreign_get_suffixes()` is only declared to FFI when libvips 8.8 or later is - * loaded, so an older build reports an empty list and callers probe instead. + * This describes the loaded build rather than any particular image, so it is queried + * once. `vips_foreign_get_suffixes()` is only declared to FFI by libvips 8.8 and + * later, and an older build reports an empty list. * * @since 7.2.0 * - * @return string[] Extensions including the leading dot, or an empty array when the - * list cannot be determined. + * @return string[] Extensions including the leading dot. */ protected static function get_save_suffixes() { - if ( isset( self::$save_suffixes ) ) { - return self::$save_suffixes; + static $suffixes = null; + + if ( null !== $suffixes ) { + return $suffixes; } $suffixes = array(); try { if ( version_compare( Jcupitt\Vips\Config::version(), '8.8', '>=' ) ) { - // The returned list is NULL-terminated and owned by the caller. These two - // functions are declared to libvips rather than to PHP, so PHPStan cannot - // see them. + // The returned list is NULL-terminated and owned by the caller. // @phpstan-ignore method.notFound (Declared in the libvips FFI cdef.) $all = Jcupitt\Vips\FFI::vips()->vips_foreign_get_suffixes(); @@ -234,8 +192,6 @@ protected static function get_save_suffixes() { $suffixes = array(); } - self::$save_suffixes = $suffixes; - return $suffixes; } From e98bbf9023232a4697856037a282ae8879e75719 Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Sat, 26 Sep 2026 07:56:09 -0600 Subject: [PATCH 53/84] Vips: Cache the save suffix list in a property --- .../class-wp-image-editor-vips.php | 26 ++++++++++++------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index 8f7097d21a254..2a7198cc91def 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -67,6 +67,16 @@ class WP_Image_Editor_Vips extends WP_Image_Editor { */ protected static $mime_support_cache = array(); + /** + * Extensions libvips can save images to, including the leading dot. + * + * Null until it has been queried. An empty array means the query was unavailable or + * failed, in which case every format falls back to being probed by encoding. + * + * @var string[]|null + */ + protected static $save_suffixes; + /** * Checks to see if current environment supports VIPS. * @@ -165,13 +175,11 @@ public static function supports_mime_type( $mime_type ) { * @return string[] Extensions including the leading dot. */ protected static function get_save_suffixes() { - static $suffixes = null; - - if ( null !== $suffixes ) { - return $suffixes; + if ( null !== self::$save_suffixes ) { + return self::$save_suffixes; } - $suffixes = array(); + self::$save_suffixes = array(); try { if ( version_compare( Jcupitt\Vips\Config::version(), '8.8', '>=' ) ) { @@ -180,19 +188,19 @@ protected static function get_save_suffixes() { $all = Jcupitt\Vips\FFI::vips()->vips_foreign_get_suffixes(); for ( $i = 0; null !== $all[ $i ]; $i++ ) { - $suffixes[] = strtolower( \FFI::string( $all[ $i ] ) ); + self::$save_suffixes[] = strtolower( \FFI::string( $all[ $i ] ) ); } // @phpstan-ignore method.notFound (Declared in the glib FFI cdef.) Jcupitt\Vips\FFI::glib()->g_strfreev( $all ); - $suffixes = array_values( array_unique( $suffixes ) ); + self::$save_suffixes = array_values( array_unique( self::$save_suffixes ) ); } } catch ( Exception $e ) { - $suffixes = array(); + self::$save_suffixes = array(); } - return $suffixes; + return self::$save_suffixes; } /** From 6083de079a4a7894e88aad7586839cc00dc1f3f1 Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Sat, 26 Sep 2026 08:06:48 -0600 Subject: [PATCH 54/84] Tests: Cover streaming of lossless WebP and paletted PNG for Vips --- tests/phpunit/tests/image/editorVips.php | 74 ++++++++++++++++++++++++ 1 file changed, 74 insertions(+) diff --git a/tests/phpunit/tests/image/editorVips.php b/tests/phpunit/tests/image/editorVips.php index fea4d93a98a46..30759370233fc 100644 --- a/tests/phpunit/tests/image/editorVips.php +++ b/tests/phpunit/tests/image/editorVips.php @@ -792,6 +792,68 @@ public function test_streams() { $this->assertSame( $temp_file, $saved['path'] ); } + /** + * Tests that a paletted PNG stays paletted when it is streamed. + */ + public function test_stream_preserves_png_palette() { + $file = DIR_TESTDATA . '/images/png-tests/rabbit-time-paletted-or8.png'; + + $this->assertSame( + 3, + $this->get_png_color_type( $file ), + 'The fixture itself is not colour type 3.' + ); + + $vips_image_editor = new WP_Image_Editor_Vips( $file ); + $vips_image_editor->load(); + + /* + * stream() sends a Content-Type header, which PHPUnit turns into a warning + * because the test suite has already produced output. + */ + ob_start(); + $result = @$vips_image_editor->stream( 'image/png' ); + $buffer = ob_get_clean(); + + $this->assertTrue( $result ); + + $streamed_file = tempnam( get_temp_dir(), 'vips_stream_palette_' ) . '.png'; + file_put_contents( $streamed_file, $buffer ); + $color_type = $this->get_png_color_type( $streamed_file ); + unlink( $streamed_file ); + + $this->assertSame( + 3, + $color_type, + 'The streamed PNG should keep the palette its source had.' + ); + } + + /** + * Tests that a lossless WebP is not streamed as a lossy one. + */ + public function test_stream_preserves_lossless_webp() { + $file = DIR_TESTDATA . '/images/webp-lossless.webp'; + + $this->assertTrue( + $this->is_lossless_webp( file_get_contents( $file ) ), + 'The fixture itself is not a lossless WebP.' + ); + + $vips_image_editor = new WP_Image_Editor_Vips( $file ); + $vips_image_editor->load(); + + ob_start(); + $result = @$vips_image_editor->stream( 'image/webp' ); + $buffer = ob_get_clean(); + + $this->assertTrue( $result ); + $this->assertTrue( + $this->is_lossless_webp( $buffer ), + 'A lossless WebP should not be streamed as a lossy one.' + ); + } + /** * Tests that an image created with WP_Image_Editor_Vips preserves alpha. */ @@ -972,6 +1034,18 @@ private function get_png_color_type( $file ) { return ord( file_get_contents( $file, false, null, 25, 1 ) ); } + /** + * Whether a WebP image is encoded losslessly. + * + * A lossless WebP carries its bitstream in a VP8L chunk, where a lossy one uses VP8. + * + * @param string $contents The contents of a WebP file. + * @return bool Whether the image is lossless. + */ + private function is_lossless_webp( $contents ) { + return false !== strpos( $contents, 'VP8L' ); + } + /** * Tests that alpha transparency survives a resize. * From 084e31a179cdfa057d339b9b6d7459720c91f64c Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Sat, 26 Sep 2026 08:08:47 -0600 Subject: [PATCH 55/84] Vips: Share the save options between saving and streaming --- .../class-wp-image-editor-vips.php | 133 +++++++++--------- tests/phpunit/tests/image/editorVips.php | 6 +- 2 files changed, 73 insertions(+), 66 deletions(-) diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index 2a7198cc91def..c5b92842b1568 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -757,6 +757,73 @@ protected function get_save_bit_depth( $image, $mime_type ) { return null; } + /** + * Returns the libvips save options for a mime type. + * + * Saving and streaming share these because the options describe how to encode this + * image in this format, which does not depend on where the bytes are going. Only + * stripping metadata is save-specific, since it is what a resized image is expected + * to lose when it is written to the media library. + * + * @since 7.2.0 + * + * @param Jcupitt\Vips\Image $image The image being written. + * @param string $mime_type The mime type it is being written as. + * @param bool $strip_meta Optional. Whether to strip metadata, for the + * encoders that accept the option. Default false. + * @return array Options passed to `writeToBuffer()` or `writeToFile()`. + */ + protected function get_save_options( $image, $mime_type, $strip_meta = false ) { + $options = array(); + + switch ( $mime_type ) { + case 'image/jpeg': + case 'image/avif': + $options['Q'] = $this->get_quality(); + $options['strip'] = $strip_meta; + break; + + case 'image/webp': + $options['Q'] = $this->get_quality(); + $options['strip'] = $strip_meta; + + // A lossless WebP has no quality to trade away, so it is re-saved losslessly. + if ( $this->lossless ) { + $options['lossless'] = true; + } + break; + + case 'image/png': + // PNG is lossless, so there is no quality to trade away, and the Imagick + // editor saves at maximum deflate compression. Deriving a level from the + // quality instead wrote files far larger than the source they came from. + $options['compression'] = 9; + $options['strip'] = $strip_meta; + + // Asking for a palette back keeps an indexed PNG indexed. Without it the + // resized image is written as true colour, which is much larger than the + // file it came from. The option requires libvips 8.13. + if ( $this->paletted && version_compare( Jcupitt\Vips\Config::version(), '8.13', '>=' ) ) { + $options['palette'] = true; + } + break; + + case 'image/gif': + $options['strip'] = $strip_meta; + break; + } + + // Of the formats handled above, only PNG and the HEIF family can be asked to + // store fewer bits per sample. + $bit_depth = $this->get_save_bit_depth( $image, $mime_type ); + + if ( null !== $bit_depth ) { + $options['bitdepth'] = $bit_depth; + } + + return $options; + } + /** * Saves current image to file. * @@ -804,9 +871,6 @@ protected function _save( $image, $filename = null, $mime_type = null ) { } try { - // Prepare save options based on mime type. - $save_options = array(); - /** This filter is documented in wp-includes/class-wp-image-editor-imagick.php */ $strip_meta = apply_filters( 'image_strip_meta', true ); @@ -815,53 +879,7 @@ protected function _save( $image, $filename = null, $mime_type = null ) { // so saving an image that was merely loaded keeps its metadata. $strip_meta = $strip_meta && $this->resized; - switch ( $mime_type ) { - case 'image/jpeg': - $save_options['Q'] = $this->get_quality(); - $save_options['strip'] = $strip_meta; - break; - - case 'image/png': - // PNG is lossless, so there is no quality to trade away, and the Imagick - // editor saves at maximum deflate compression. Deriving a level from the - // quality instead wrote files far larger than the source they came from. - $save_options['compression'] = 9; - $save_options['strip'] = $strip_meta; - - // Asking for a palette back keeps an indexed PNG indexed. Without it the - // resized image is written as true colour, which is much larger than the - // file it came from. The option requires libvips 8.13. - if ( $this->paletted && version_compare( Jcupitt\Vips\Config::version(), '8.13', '>=' ) ) { - $save_options['palette'] = true; - } - break; - - case 'image/webp': - $save_options['Q'] = $this->get_quality(); - $save_options['strip'] = $strip_meta; - - if ( $this->lossless ) { - $save_options['lossless'] = true; - } - break; - - case 'image/gif': - $save_options['strip'] = $strip_meta; - break; - - case 'image/avif': - $save_options['Q'] = $this->get_quality(); - $save_options['strip'] = $strip_meta; - break; - } - - // Of the formats above, only PNG and the HEIF family can be asked to store - // fewer bits per sample. - $bit_depth = $this->get_save_bit_depth( $image, $mime_type ); - - if ( null !== $bit_depth ) { - $save_options['bitdepth'] = $bit_depth; - } + $save_options = $this->get_save_options( $image, $mime_type, $strip_meta ); if ( wp_is_stream( $filename ) ) { $buffer = $image->writeToBuffer( '.' . $extension, $save_options ); @@ -930,20 +948,7 @@ public function stream( $mime_type = null ) { list( $filename, $extension, $mime_type ) = $this->get_output_format( null, $mime_type ); try { - $save_options = array(); - - switch ( $mime_type ) { - case 'image/png': - // PNG is lossless; see the note in _save(). - $save_options['compression'] = 9; - break; - - case 'image/webp': - case 'image/jpeg': - case 'image/avif': - $save_options['Q'] = $this->get_quality(); - break; - } + $save_options = $this->get_save_options( $this->image, $mime_type ); // Get the image buffer. $buffer = $this->image->writeToBuffer( '.' . $extension, $save_options ); diff --git a/tests/phpunit/tests/image/editorVips.php b/tests/phpunit/tests/image/editorVips.php index 30759370233fc..7a4c903cdd772 100644 --- a/tests/phpunit/tests/image/editorVips.php +++ b/tests/phpunit/tests/image/editorVips.php @@ -808,10 +808,11 @@ public function test_stream_preserves_png_palette() { $vips_image_editor->load(); /* - * stream() sends a Content-Type header, which PHPUnit turns into a warning - * because the test suite has already produced output. + * stream() sends a Content-Type header, which cannot be set once PHPUnit has + * produced output, so the warning it raises is unavoidable here. */ ob_start(); + // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- Warning is unavoidable. $result = @$vips_image_editor->stream( 'image/png' ); $buffer = ob_get_clean(); @@ -844,6 +845,7 @@ public function test_stream_preserves_lossless_webp() { $vips_image_editor->load(); ob_start(); + // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- Warning is unavoidable. $result = @$vips_image_editor->stream( 'image/webp' ); $buffer = ob_get_clean(); From 4bb837c7be86179d8d800b39d027d53694d670f5 Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Sat, 26 Sep 2026 08:16:04 -0600 Subject: [PATCH 56/84] Vips: reorder some methods --- .../class-wp-image-editor-vips.php | 274 +++++++++--------- 1 file changed, 137 insertions(+), 137 deletions(-) diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index c5b92842b1568..19dac6a869f10 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -687,143 +687,6 @@ protected function reset_exif_orientation() { $this->image = $this->image->autorot(); } - /** - * Returns the bit depth that a libvips band format stores. - * - * @since 7.2.0 - * - * @param string $format A libvips band format, such as `uchar` or `ushort`. - * @return int The bit depth of that format. - */ - protected static function get_format_bit_depth( $format ) { - switch ( $format ) { - case 'ushort': - case 'short': - return 16; - case 'uint': - case 'int': - case 'float': - return 32; - case 'double': - case 'complex': - return 64; - case 'dpcomplex': - return 128; - default: - return 8; - } - } - - /** - * Returns the bit depth to save an image at, honouring `image_max_bit_depth`. - * - * libvips stores samples in a fixed set of band formats rather than at an arbitrary - * bit depth, and only some encoders accept a bit depth at all. This picks the nearest - * depth the encoder offers and returns null for everything else, which leaves the - * image at its own depth. - * - * @since 7.2.0 - * - * @param Jcupitt\Vips\Image $image The image being saved. - * @param string $mime_type The mime type it is being saved as. - * @return int|null The bit depth to save at, or null to leave it unchanged. - */ - protected function get_save_bit_depth( $image, $mime_type ) { - $image_depth = self::get_format_bit_depth( $image->format ); - - /** This filter is documented in wp-includes/class-wp-image-editor-imagick.php */ - $max_depth = apply_filters( 'image_max_bit_depth', $image_depth, $image_depth ); - - if ( $max_depth >= $image_depth ) { - return null; - } - - switch ( $mime_type ) { - case 'image/png': - // pngsave writes 8 or 16 bits per sample. - return $max_depth <= 8 ? 8 : null; - - case 'image/avif': - case 'image/heic': - case 'image/heif': - // heifsave accepts 8, 10 or 12 bits per sample. - if ( $max_depth <= 8 ) { - return 8; - } - - return $max_depth <= 10 ? 10 : 12; - } - - return null; - } - - /** - * Returns the libvips save options for a mime type. - * - * Saving and streaming share these because the options describe how to encode this - * image in this format, which does not depend on where the bytes are going. Only - * stripping metadata is save-specific, since it is what a resized image is expected - * to lose when it is written to the media library. - * - * @since 7.2.0 - * - * @param Jcupitt\Vips\Image $image The image being written. - * @param string $mime_type The mime type it is being written as. - * @param bool $strip_meta Optional. Whether to strip metadata, for the - * encoders that accept the option. Default false. - * @return array Options passed to `writeToBuffer()` or `writeToFile()`. - */ - protected function get_save_options( $image, $mime_type, $strip_meta = false ) { - $options = array(); - - switch ( $mime_type ) { - case 'image/jpeg': - case 'image/avif': - $options['Q'] = $this->get_quality(); - $options['strip'] = $strip_meta; - break; - - case 'image/webp': - $options['Q'] = $this->get_quality(); - $options['strip'] = $strip_meta; - - // A lossless WebP has no quality to trade away, so it is re-saved losslessly. - if ( $this->lossless ) { - $options['lossless'] = true; - } - break; - - case 'image/png': - // PNG is lossless, so there is no quality to trade away, and the Imagick - // editor saves at maximum deflate compression. Deriving a level from the - // quality instead wrote files far larger than the source they came from. - $options['compression'] = 9; - $options['strip'] = $strip_meta; - - // Asking for a palette back keeps an indexed PNG indexed. Without it the - // resized image is written as true colour, which is much larger than the - // file it came from. The option requires libvips 8.13. - if ( $this->paletted && version_compare( Jcupitt\Vips\Config::version(), '8.13', '>=' ) ) { - $options['palette'] = true; - } - break; - - case 'image/gif': - $options['strip'] = $strip_meta; - break; - } - - // Of the formats handled above, only PNG and the HEIF family can be asked to - // store fewer bits per sample. - $bit_depth = $this->get_save_bit_depth( $image, $mime_type ); - - if ( null !== $bit_depth ) { - $options['bitdepth'] = $bit_depth; - } - - return $options; - } - /** * Saves current image to file. * @@ -962,4 +825,141 @@ public function stream( $mime_type = null ) { return new WP_Error( 'image_stream_error', $e->getMessage() ); } } + + /** + * Returns the libvips save options for a mime type. + * + * Saving and streaming share these because the options describe how to encode this + * image in this format, which does not depend on where the bytes are going. Only + * stripping metadata is save-specific, since it is what a resized image is expected + * to lose when it is written to the media library. + * + * @since 7.2.0 + * + * @param Jcupitt\Vips\Image $image The image being written. + * @param string $mime_type The mime type it is being written as. + * @param bool $strip_meta Optional. Whether to strip metadata, for the + * encoders that accept the option. Default false. + * @return array Options passed to `writeToBuffer()` or `writeToFile()`. + */ + protected function get_save_options( $image, $mime_type, $strip_meta = false ) { + $options = array(); + + switch ( $mime_type ) { + case 'image/jpeg': + case 'image/avif': + $options['Q'] = $this->get_quality(); + $options['strip'] = $strip_meta; + break; + + case 'image/webp': + $options['Q'] = $this->get_quality(); + $options['strip'] = $strip_meta; + + // A lossless WebP has no quality to trade away, so it is re-saved losslessly. + if ( $this->lossless ) { + $options['lossless'] = true; + } + break; + + case 'image/png': + // PNG is lossless, so there is no quality to trade away, and the Imagick + // editor saves at maximum deflate compression. Deriving a level from the + // quality instead wrote files far larger than the source they came from. + $options['compression'] = 9; + $options['strip'] = $strip_meta; + + // Asking for a palette back keeps an indexed PNG indexed. Without it the + // resized image is written as true colour, which is much larger than the + // file it came from. The option requires libvips 8.13. + if ( $this->paletted && version_compare( Jcupitt\Vips\Config::version(), '8.13', '>=' ) ) { + $options['palette'] = true; + } + break; + + case 'image/gif': + $options['strip'] = $strip_meta; + break; + } + + // Of the formats handled above, only PNG and the HEIF family can be asked to + // store fewer bits per sample. + $bit_depth = $this->get_save_bit_depth( $image, $mime_type ); + + if ( null !== $bit_depth ) { + $options['bitdepth'] = $bit_depth; + } + + return $options; + } + + /** + * Returns the bit depth to save an image at, honouring `image_max_bit_depth`. + * + * libvips stores samples in a fixed set of band formats rather than at an arbitrary + * bit depth, and only some encoders accept a bit depth at all. This picks the nearest + * depth the encoder offers and returns null for everything else, which leaves the + * image at its own depth. + * + * @since 7.2.0 + * + * @param Jcupitt\Vips\Image $image The image being saved. + * @param string $mime_type The mime type it is being saved as. + * @return int|null The bit depth to save at, or null to leave it unchanged. + */ + protected function get_save_bit_depth( $image, $mime_type ) { + $image_depth = self::get_format_bit_depth( $image->format ); + + /** This filter is documented in wp-includes/class-wp-image-editor-imagick.php */ + $max_depth = apply_filters( 'image_max_bit_depth', $image_depth, $image_depth ); + + if ( $max_depth >= $image_depth ) { + return null; + } + + switch ( $mime_type ) { + case 'image/png': + // pngsave writes 8 or 16 bits per sample. + return $max_depth <= 8 ? 8 : null; + + case 'image/avif': + case 'image/heic': + case 'image/heif': + // heifsave accepts 8, 10 or 12 bits per sample. + if ( $max_depth <= 8 ) { + return 8; + } + + return $max_depth <= 10 ? 10 : 12; + } + + return null; + } + + /** + * Returns the bit depth that a libvips band format stores. + * + * @since 7.2.0 + * + * @param string $format A libvips band format, such as `uchar` or `ushort`. + * @return int The bit depth of that format. + */ + protected static function get_format_bit_depth( $format ) { + switch ( $format ) { + case 'ushort': + case 'short': + return 16; + case 'uint': + case 'int': + case 'float': + return 32; + case 'double': + case 'complex': + return 64; + case 'dpcomplex': + return 128; + default: + return 8; + } + } } From 8a51aefeae133aeaa000e87853310316b64e216d Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Sat, 26 Sep 2026 08:22:39 -0600 Subject: [PATCH 57/84] Vips: Determine the environment support once --- src/wp-includes/class-wp-image-editor-vips.php | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index 19dac6a869f10..aebbc084c8d78 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -77,6 +77,16 @@ class WP_Image_Editor_Vips extends WP_Image_Editor { */ protected static $save_suffixes; + /** + * Whether the environment can run libvips. + * + * Null until it has been checked. The answer cannot change during a request, and + * test() is reached once for every mime type that is asked about. + * + * @var bool|null + */ + protected static $environment_supported; + /** * Checks to see if current environment supports VIPS. * @@ -86,6 +96,12 @@ class WP_Image_Editor_Vips extends WP_Image_Editor { * @return bool */ public static function test( $args = array() ) { + if ( null !== self::$environment_supported ) { + return self::$environment_supported; + } + + self::$environment_supported = false; + // Check if FFI extension is available. if ( ! extension_loaded( 'ffi' ) ) { return false; @@ -111,6 +127,8 @@ public static function test( $args = array() ) { return false; } + self::$environment_supported = true; + return true; } From ebd6d5c4c482c7ab26d801ecfa95c48cf8b36d48 Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Sat, 26 Sep 2026 08:23:30 -0600 Subject: [PATCH 58/84] Tests: Cover the resized flag after generating sub-sizes --- .../data/images/test-image-iptc-25x25.jpg | Bin 0 -> 851 bytes tests/phpunit/tests/image/editorVips.php | 37 ++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 tests/phpunit/data/images/test-image-iptc-25x25.jpg diff --git a/tests/phpunit/data/images/test-image-iptc-25x25.jpg b/tests/phpunit/data/images/test-image-iptc-25x25.jpg new file mode 100644 index 0000000000000000000000000000000000000000..677e4c5d2ccd054167fac20863eeef406168edd3 GIT binary patch literal 851 zcmex=UWoRTYpSj6kiN9GrrjoPsJ6A`&VjgZ~E@1UVQa86=q* zl^B==8JPtc{~uwHXJBAtWds8TC}3n_W?^Mx=iubx1}fMpz`(@F%*@2X%nI}aP<1U( zo`FS>RY=j$kxe)-kzJ`!#HexNLJno8jR!@8E`CrkPAY2R|V^&07y2J$~}^+4C1K zUw!=a`ODXD-+%o41@ado12e>1Koa6HG=B*K{l&z>!py=B@)sjhIS?}oval)|vI#i` zvL_Y_D;YI%h&WALxbYyTvT@J{(WIh_Tw*FF4^=;cyax6eaUN?T%V%(pA^dfVfrpt9 z7|;X zZk_e&S!f$a;F3vh790ywCcj}Y{aoIsI{ipI|GPc@*-I^03y;qasU7T literal 0 HcmV?d00001 diff --git a/tests/phpunit/tests/image/editorVips.php b/tests/phpunit/tests/image/editorVips.php index 7a4c903cdd772..94b07f9da9eaa 100644 --- a/tests/phpunit/tests/image/editorVips.php +++ b/tests/phpunit/tests/image/editorVips.php @@ -995,6 +995,43 @@ public function test_metadata_is_preserved_when_saving_without_resizing() { $this->assertNotEmpty( $saved['caption'], 'Metadata should be preserved when the image is not resized.' ); } + /** + * Tests that generating sub-sizes leaves the editor holding an unresized image. + * + * make_subsize() puts the image and the size back, so the editor is left holding the + * image it was loaded with. A save after that is a save of an unresized image, and + * should keep its metadata for the same reason a plain load-and-save does. + * + * @requires extension exif + */ + public function test_multi_resize_does_not_strip_metadata_on_a_later_save() { + $file = DIR_TESTDATA . '/images/test-image-iptc.jpg'; + + $vips_image_editor = new WP_Image_Editor_Vips( $file ); + $vips_image_editor->load(); + + $subsizes = $vips_image_editor->multi_resize( + array( + array( + 'width' => 25, + 'height' => 25, + ), + ) + ); + $this->assertNotEmpty( $subsizes ); + + $saved_file = tempnam( get_temp_dir(), 'vips_meta_' ) . '.jpg'; + $vips_image_editor->save( $saved_file ); + + $saved = wp_read_image_metadata( $saved_file ); + unlink( $saved_file ); + + $this->assertNotEmpty( + $saved['caption'], + 'Metadata should be preserved when the editor was only asked for sub-sizes.' + ); + } + /** * Tests that a single loaded image can be read more than once. * From b3093e818710f7962aac5ae4a2b313a7202351db Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Sat, 26 Sep 2026 08:23:56 -0600 Subject: [PATCH 59/84] Vips: Restore the resized flag in make_subsize --- src/wp-includes/class-wp-image-editor-vips.php | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index aebbc084c8d78..88f10af85c334 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -467,8 +467,9 @@ public function make_subsize( $size_data ) { return new WP_Error( 'image_subsize_create_error', __( 'Cannot resize the image. Both width and height are not set.' ) ); } - $orig_size = $this->size; - $orig_image = $this->image; + $orig_size = $this->size; + $orig_image = $this->image; + $orig_resized = $this->resized; $size_data['width'] = isset( $size_data['width'] ) ? $size_data['width'] : null; $size_data['height'] = isset( $size_data['height'] ) ? $size_data['height'] : null; @@ -481,8 +482,9 @@ public function make_subsize( $size_data ) { $resized = $this->_resize( $size_data['width'], $size_data['height'], $size_data['crop'] ); if ( is_wp_error( $resized ) ) { - $this->image = $orig_image; - $this->size = $orig_size; + $this->image = $orig_image; + $this->size = $orig_size; + $this->resized = $orig_resized; return $resized; } @@ -490,9 +492,11 @@ public function make_subsize( $size_data ) { $saved = $this->_save( $resized ); // The editor keeps the image it was loaded with, so further sub-sizes are all - // derived from the same original rather than from the previous sub-size. - $this->image = $orig_image; - $this->size = $orig_size; + // derived from the same original rather than from the previous sub-size, and a + // save afterwards is still a save of an unresized image. + $this->image = $orig_image; + $this->size = $orig_size; + $this->resized = $orig_resized; if ( ! is_wp_error( $saved ) ) { unset( $saved['path'] ); From df19ed3d979d6a2cd8592f688e464fe781da949f Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Sat, 26 Sep 2026 08:46:43 -0600 Subject: [PATCH 60/84] Vips: Memoize the environment check without a property --- .../class-wp-image-editor-vips.php | 23 ++++++++----------- 1 file changed, 9 insertions(+), 14 deletions(-) diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index 88f10af85c334..7c443bdc7ab83 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -77,30 +77,25 @@ class WP_Image_Editor_Vips extends WP_Image_Editor { */ protected static $save_suffixes; - /** - * Whether the environment can run libvips. - * - * Null until it has been checked. The answer cannot change during a request, and - * test() is reached once for every mime type that is asked about. - * - * @var bool|null - */ - protected static $environment_supported; - /** * Checks to see if current environment supports VIPS. * + * The answer cannot change during a request, and the check is reached once for every + * mime type that is asked about, so it is made once. + * * @since 7.2.0 * * @param array $args * @return bool */ public static function test( $args = array() ) { - if ( null !== self::$environment_supported ) { - return self::$environment_supported; + static $supported = null; + + if ( null !== $supported ) { + return $supported; } - self::$environment_supported = false; + $supported = false; // Check if FFI extension is available. if ( ! extension_loaded( 'ffi' ) ) { @@ -127,7 +122,7 @@ public static function test( $args = array() ) { return false; } - self::$environment_supported = true; + $supported = true; return true; } From 6f8f8e5c41978dd9e13fc7ca0f518c0adf8e196f Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Sat, 26 Sep 2026 08:52:36 -0600 Subject: [PATCH 61/84] Vips: Make the bit depth helper static --- src/wp-includes/class-wp-image-editor-vips.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index 7c443bdc7ab83..fd6198e5bad0f 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -901,7 +901,7 @@ protected function get_save_options( $image, $mime_type, $strip_meta = false ) { // Of the formats handled above, only PNG and the HEIF family can be asked to // store fewer bits per sample. - $bit_depth = $this->get_save_bit_depth( $image, $mime_type ); + $bit_depth = self::get_save_bit_depth( $image, $mime_type ); if ( null !== $bit_depth ) { $options['bitdepth'] = $bit_depth; @@ -924,7 +924,7 @@ protected function get_save_options( $image, $mime_type, $strip_meta = false ) { * @param string $mime_type The mime type it is being saved as. * @return int|null The bit depth to save at, or null to leave it unchanged. */ - protected function get_save_bit_depth( $image, $mime_type ) { + protected static function get_save_bit_depth( $image, $mime_type ) { $image_depth = self::get_format_bit_depth( $image->format ); /** This filter is documented in wp-includes/class-wp-image-editor-imagick.php */ From e2b1021df0aa30ac933c9d8a2d8f4c8840e300ce Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Wed, 7 Oct 2026 08:47:52 -0600 Subject: [PATCH 62/84] Vips: Require libvips 8.13 --- src/wp-includes/class-wp-image-editor-vips.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index fd6198e5bad0f..460cbd80cdd7b 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -114,8 +114,8 @@ public static function test( $args = array() ) { return false; } - // Require libvips 8.7 or later - if ( version_compare( $version, '8.7', '<' ) ) { + // Require libvips 8.13 or later. + if ( version_compare( $version, '8.13', '<' ) ) { return false; } } catch ( Exception $e ) { From 7d931dc85aa0e855fb81cb2643fc2369275a51e9 Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Wed, 7 Oct 2026 08:48:04 -0600 Subject: [PATCH 63/84] Vips: Add a filterable resampling kernel --- .../class-wp-image-editor-vips.php | 37 ++++++++++++++++++- 1 file changed, 35 insertions(+), 2 deletions(-) diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index 460cbd80cdd7b..3ad6b68ee9bfa 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -368,6 +368,27 @@ public function resize( $max_w, $max_h, $crop = false ) { return true; } + /** + * Returns the libvips resampling kernel to use when resizing. + * + * @since 7.2.0 + * + * @return string A libvips kernel name. + */ + protected function get_resampling_kernel() { + /** + * Filters the libvips resampling kernel used when resizing. + * + * @since 7.2.0 + * + * @param string $kernel A libvips kernel name. Default 'lanczos3'. + */ + $kernel = apply_filters( 'wp_image_editor_vips_resampling_kernel', 'lanczos3' ); + $allowed = array( 'nearest', 'linear', 'cubic', 'mitchell', 'lanczos2', 'lanczos3', 'mks2013', 'mks2021' ); + + return in_array( $kernel, $allowed, true ) ? $kernel : 'lanczos3'; + } + /** * Resizes the image and returns it, leaving `$this->image` alone. * @@ -400,7 +421,13 @@ protected function _resize( $max_w, $max_h, $crop = false ) { // Then scale that region to the destination dimensions. if ( (int) $src_w !== $dst_w || (int) $src_h !== $dst_h ) { - $image = $image->resize( $dst_w / (int) $src_w, array( 'vscale' => $dst_h / (int) $src_h ) ); + $image = $image->resize( + $dst_w / (int) $src_w, + array( + 'vscale' => $dst_h / (int) $src_h, + 'kernel' => $this->get_resampling_kernel(), + ) + ); } $this->update_size( $dst_w, $dst_h ); @@ -548,7 +575,13 @@ public function crop( $src_x, $src_y, $src_w, $src_h, $dst_w = null, $dst_h = nu if ( $actual_src_w !== $dst_w || $actual_src_h !== $dst_h ) { $h_scale = $dst_w / $actual_src_w; $v_scale = $dst_h / $actual_src_h; - $cropped = $cropped->resize( $h_scale, array( 'vscale' => $v_scale ) ); + $cropped = $cropped->resize( + $h_scale, + array( + 'vscale' => $v_scale, + 'kernel' => $this->get_resampling_kernel(), + ) + ); } $this->image = $cropped; From 726a01bacbbf025ef8662b1e4bd2d343ca265d70 Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Wed, 7 Oct 2026 08:48:15 -0600 Subject: [PATCH 64/84] Vips: Optimise JPEG Huffman coding --- src/wp-includes/class-wp-image-editor-vips.php | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index 3ad6b68ee9bfa..84ca820a777eb 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -897,6 +897,11 @@ protected function get_save_options( $image, $mime_type, $strip_meta = false ) { switch ( $mime_type ) { case 'image/jpeg': + $options['Q'] = $this->get_quality(); + $options['strip'] = $strip_meta; + $options['optimize_coding'] = true; + break; + case 'image/avif': $options['Q'] = $this->get_quality(); $options['strip'] = $strip_meta; From 9b303c567e70a520f47dbd27402fb391db9e3427 Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Wed, 7 Oct 2026 08:48:27 -0600 Subject: [PATCH 65/84] Vips: Apply image_save_progressive as interlace --- src/wp-includes/class-wp-image-editor-vips.php | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index 84ca820a777eb..22fce34e02fc0 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -900,6 +900,7 @@ protected function get_save_options( $image, $mime_type, $strip_meta = false ) { $options['Q'] = $this->get_quality(); $options['strip'] = $strip_meta; $options['optimize_coding'] = true; + $options['interlace'] = (bool) apply_filters( 'image_save_progressive', false, $mime_type ); break; case 'image/avif': @@ -923,6 +924,7 @@ protected function get_save_options( $image, $mime_type, $strip_meta = false ) { // quality instead wrote files far larger than the source they came from. $options['compression'] = 9; $options['strip'] = $strip_meta; + $options['interlace'] = (bool) apply_filters( 'image_save_progressive', false, $mime_type ); // Asking for a palette back keeps an indexed PNG indexed. Without it the // resized image is written as true colour, which is much larger than the @@ -934,6 +936,11 @@ protected function get_save_options( $image, $mime_type, $strip_meta = false ) { case 'image/gif': $options['strip'] = $strip_meta; + + // gifsave gained the interlace option in libvips 8.14. + if ( version_compare( Jcupitt\Vips\Config::version(), '8.14', '>=' ) ) { + $options['interlace'] = (bool) apply_filters( 'image_save_progressive', false, $mime_type ); + } break; } From 202c6ab7bb0cf1272a0b8ea041d56687238153df Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Wed, 7 Oct 2026 08:48:39 -0600 Subject: [PATCH 66/84] Vips: Default AVIF encoding to effort 3 --- src/wp-includes/class-wp-image-editor-vips.php | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index 22fce34e02fc0..7f8dcc5221c58 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -904,8 +904,19 @@ protected function get_save_options( $image, $mime_type, $strip_meta = false ) { break; case 'image/avif': - $options['Q'] = $this->get_quality(); - $options['strip'] = $strip_meta; + $options['Q'] = $this->get_quality(); + $options['strip'] = $strip_meta; + /** + * Filters the libvips effort used when encoding AVIF. + * + * A higher effort is more CPU per image, and WordPress's typical 30s + * PHP-FPM limit can be reached on large images at the libvips default. + * + * @since 7.2.0 + * + * @param int $effort A value between 0 and 9. Default 3. + */ + $options['effort'] = max( 0, min( 9, (int) apply_filters( 'wp_image_editor_vips_avif_effort', 3 ) ) ); break; case 'image/webp': From c33d6479e8188ef52225b2cc97488f56b239aabc Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Wed, 7 Oct 2026 08:49:13 -0600 Subject: [PATCH 67/84] Vips: Reject truncated images on load --- src/wp-includes/class-wp-image-editor-vips.php | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index 7f8dcc5221c58..d0462c4400d90 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -236,15 +236,23 @@ public function load() { wp_raise_memory_limit( 'image' ); try { + /* + * Reject truncated images, as the Imagick and GD editors do. JPEG is the + * exception: damage there is recoverable, and the other editors fill it, so + * a truncated JPEG still loads. + */ + $load_mime = wp_is_stream( $this->file ) ? '' : wp_get_image_mime( $this->file ); + $load_options = array( 'fail_on' => ( 'image/jpeg' === $load_mime ) ? 'none' : 'truncated' ); + // Load the image. if ( wp_is_stream( $this->file ) ) { $file_contents = file_get_contents( $this->file ); if ( false === $file_contents ) { return new WP_Error( 'error_loading_image', __( 'File does not exist?' ), $this->file ); } - $this->image = Jcupitt\Vips\Image::newFromBuffer( $file_contents ); + $this->image = Jcupitt\Vips\Image::newFromBuffer( $file_contents, '', $load_options ); } else { - $this->image = Jcupitt\Vips\Image::newFromFile( $this->file ); + $this->image = Jcupitt\Vips\Image::newFromFile( $this->file, $load_options ); } // Get image size. From 9a10a3aee9f2f4efe26dc4e4443870a7a67b1615 Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Wed, 7 Oct 2026 08:51:42 -0600 Subject: [PATCH 68/84] Vips: Restrict loaders and block untrusted ones --- .../class-wp-image-editor-vips.php | 73 +++++++++++++++++++ 1 file changed, 73 insertions(+) diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index d0462c4400d90..ca80b8da1daec 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -107,6 +107,14 @@ public static function test( $args = array() ) { return false; } + /* + * libvips hands a file to whichever loader claims it, and several of them execute + * code or resolve external references (SVG, PDF, DZI). The block is process-wide + * and is read by libvips when it initialises, which the call below does, so it has + * to be set first. + */ + self::block_untrusted_loaders(); + // Try to get the libvips version to confirm it's working. try { $version = Jcupitt\Vips\Config::version(); @@ -127,6 +135,53 @@ public static function test( $args = array() ) { return true; } + /** + * Processes the libvips loaders that may be used to decode an image. + * + * `vips-loader` holds the name of the operation libvips chose for the file. + * + * @since 7.2.0 + * + * @return string[] Loader operation names. + */ + protected static function get_allowed_loaders() { + /** + * Filters the libvips loaders the VIPS image editor will decode with. + * + * The allowlist exists because libvips selects a loader from the file's magic + * bytes. Loaders vary in how much trust they require, and some are not usable as + * image editors at all, so the set is limited to the raster image loaders. + * + * @since 7.2.0 + * + * @param string[] $loaders Loader operation names. + */ + return apply_filters( + 'wp_image_editor_vips_allowed_loaders', + array( + 'jpegload', + 'pngload', + 'webpload', + 'tiffload', + 'gifload', + 'heifload', + ) + ); + } + + /** + * Blocks libvips loaders that are considered untrusted. + * + * The variable is read when libvips initialises, and the caller is the first thing to + * touch the library, so it is set here rather than at load time. This is a second + * layer: get_allowed_loaders() is what the editor relies on. + * + * @since 7.2.0 + */ + protected static function block_untrusted_loaders() { + putenv( 'VIPS_BLOCK_UNTRUSTED=1' ); + } + /** * Checks to see if editor supports the mime-type specified. * @@ -255,6 +310,24 @@ public function load() { $this->image = Jcupitt\Vips\Image::newFromFile( $this->file, $load_options ); } + /* + * libvips picks the loader from the file's magic bytes, which is not necessarily + * the format WordPress believes the file to be. Refuse anything that was decoded + * by a loader the editor does not support, rather than editing it through a code + * path that was never checked. + * + * The operation is named per input variant -- a file is decoded by `jpegload`, a + * buffer by `jpegload_buffer`, a source by `jpegload_source` -- so the suffix is + * dropped and the allowlist names one operation per format. + */ + $loader = preg_replace( '/_(buffer|source)$/', '', (string) $this->image->get( 'vips-loader' ) ); + + if ( ! in_array( $loader, self::get_allowed_loaders(), true ) ) { + $this->image = null; + + return new WP_Error( 'invalid_image', __( 'Image type not supported.' ), $this->file ); + } + // Get image size. $width = $this->image->width; $height = $this->image->height; From f073cb3e177fba45ad18f4dd98603e78029464a2 Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Wed, 7 Oct 2026 08:52:05 -0600 Subject: [PATCH 69/84] Vips: Cap the decoded pixel count --- .../class-wp-image-editor-vips.php | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index ca80b8da1daec..1b2071de842df 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -336,6 +336,38 @@ public function load() { return new WP_Error( 'invalid_image', __( 'Could not read image size.' ), $this->file ); } + /** + * Filters the largest image the VIPS image editor will decode, in pixels. + * + * libvips reads pixels lazily, so a small file can announce enormous + * dimensions and only cost the memory it claims once something touches the + * pixels. The dimensions are known before that happens, so an oversized image + * is refused here rather than after a decoding attempt has exhausted memory. + * + * The default is the largest image a JPEG can describe, which is also the + * largest size the other editors handle without special configuration. + * + * @since 7.2.0 + * + * @param int $max_pixels Maximum number of pixels. Default 16383 * 16383. + */ + $max_pixels = (int) apply_filters( 'wp_image_editor_vips_max_pixels', 16383 * 16383 ); + + if ( $width * $height > $max_pixels ) { + $this->image = null; + + return new WP_Error( + 'invalid_image', + sprintf( + /* translators: 1: Image width in pixels, 2: Image height in pixels. */ + __( 'Image is too large to process (%1$d x %2$d pixels).' ), + $width, + $height + ), + $this->file + ); + } + // Set the mime type. // // This must not use wp_getimagesize(): for HEIC and AVIF files it falls back From 5c04394d5b55a0cb44400f9a94d9a430cdc5c65e Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Wed, 7 Oct 2026 08:57:32 -0600 Subject: [PATCH 70/84] Vips: Require libvips 8.15 The keep saver option, used to preserve colour profiles when metadata is stripped, is only available from 8.15. Raise the floor to it and drop the version branches the floor makes unreachable: the 8.8 guard around vips_foreign_get_suffixes(), the 8.13 guard around the PNG palette option, and the 8.14 guard around gifsave interlace. --- .../class-wp-image-editor-vips.php | 40 ++++++++----------- 1 file changed, 17 insertions(+), 23 deletions(-) diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index 1b2071de842df..a3608088c3aad 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -122,8 +122,9 @@ public static function test( $args = array() ) { return false; } - // Require libvips 8.13 or later. - if ( version_compare( $version, '8.13', '<' ) ) { + // Require libvips 8.15 or later, which is the first version with the `keep` + // saver option used to preserve colour profiles when metadata is stripped. + if ( version_compare( $version, '8.15', '<' ) ) { return false; } } catch ( Exception $e ) { @@ -235,8 +236,7 @@ public static function supports_mime_type( $mime_type ) { * Returns the extensions libvips can save images to. * * This describes the loaded build rather than any particular image, so it is queried - * once. `vips_foreign_get_suffixes()` is only declared to FFI by libvips 8.8 and - * later, and an older build reports an empty list. + * once. * * @since 7.2.0 * @@ -250,20 +250,18 @@ protected static function get_save_suffixes() { self::$save_suffixes = array(); try { - if ( version_compare( Jcupitt\Vips\Config::version(), '8.8', '>=' ) ) { - // The returned list is NULL-terminated and owned by the caller. - // @phpstan-ignore method.notFound (Declared in the libvips FFI cdef.) - $all = Jcupitt\Vips\FFI::vips()->vips_foreign_get_suffixes(); + // The returned list is NULL-terminated and owned by the caller. + // @phpstan-ignore method.notFound (Declared in the libvips FFI cdef.) + $all = Jcupitt\Vips\FFI::vips()->vips_foreign_get_suffixes(); - for ( $i = 0; null !== $all[ $i ]; $i++ ) { - self::$save_suffixes[] = strtolower( \FFI::string( $all[ $i ] ) ); - } + for ( $i = 0; null !== $all[ $i ]; $i++ ) { + self::$save_suffixes[] = strtolower( \FFI::string( $all[ $i ] ) ); + } - // @phpstan-ignore method.notFound (Declared in the glib FFI cdef.) - Jcupitt\Vips\FFI::glib()->g_strfreev( $all ); + // @phpstan-ignore method.notFound (Declared in the glib FFI cdef.) + Jcupitt\Vips\FFI::glib()->g_strfreev( $all ); - self::$save_suffixes = array_values( array_unique( self::$save_suffixes ) ); - } + self::$save_suffixes = array_values( array_unique( self::$save_suffixes ) ); } catch ( Exception $e ) { self::$save_suffixes = array(); } @@ -1052,19 +1050,15 @@ protected function get_save_options( $image, $mime_type, $strip_meta = false ) { // Asking for a palette back keeps an indexed PNG indexed. Without it the // resized image is written as true colour, which is much larger than the - // file it came from. The option requires libvips 8.13. - if ( $this->paletted && version_compare( Jcupitt\Vips\Config::version(), '8.13', '>=' ) ) { + // file it came from. + if ( $this->paletted ) { $options['palette'] = true; } break; case 'image/gif': - $options['strip'] = $strip_meta; - - // gifsave gained the interlace option in libvips 8.14. - if ( version_compare( Jcupitt\Vips\Config::version(), '8.14', '>=' ) ) { - $options['interlace'] = (bool) apply_filters( 'image_save_progressive', false, $mime_type ); - } + $options['strip'] = $strip_meta; + $options['interlace'] = (bool) apply_filters( 'image_save_progressive', false, $mime_type ); break; } From 8de155169b9864a5ed38f01aca966ad1144f1930 Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Wed, 7 Oct 2026 09:01:47 -0600 Subject: [PATCH 71/84] Vips: Keep colour and descriptive profiles when stripping Pass libvips a keep mask of ICC, EXIF, XMP and IPTC instead of the strip boolean, which discarded every field including the colour profile. The protected set is the one the Imagick editor protects, so a resized image no longer loses how it is meant to be rendered. The strip_meta option is now the same for every format, so it moved out of the per-format switch. --- .../class-wp-image-editor-vips.php | 28 ++++++---- tests/phpunit/tests/image/editorVips.php | 54 +++++++++++++++---- 2 files changed, 63 insertions(+), 19 deletions(-) diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index a3608088c3aad..eb531ea5f2faa 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -999,24 +999,37 @@ public function stream( $mime_type = null ) { * * @param Jcupitt\Vips\Image $image The image being written. * @param string $mime_type The mime type it is being written as. - * @param bool $strip_meta Optional. Whether to strip metadata, for the - * encoders that accept the option. Default false. + * @param bool $strip_meta Optional. Whether to reduce the metadata to the + * colour profile and the descriptive fields. + * Default false. * @return array Options passed to `writeToBuffer()` or `writeToFile()`. */ protected function get_save_options( $image, $mime_type, $strip_meta = false ) { $options = array(); + /* + * Metadata is handled the same way for every format that stores it. libvips' `strip` + * boolean drops every field, including the colour profile, which changes how the + * image renders once nothing tells the browser how to interpret the samples. The + * `keep` mask drops the rest while preserving the colour profile and the descriptive + * fields, which is the set the Imagick editor keeps. + */ + if ( $strip_meta ) { + $options['keep'] = Jcupitt\Vips\ForeignKeep::ICC + | Jcupitt\Vips\ForeignKeep::EXIF + | Jcupitt\Vips\ForeignKeep::XMP + | Jcupitt\Vips\ForeignKeep::IPTC; + } + switch ( $mime_type ) { case 'image/jpeg': $options['Q'] = $this->get_quality(); - $options['strip'] = $strip_meta; $options['optimize_coding'] = true; $options['interlace'] = (bool) apply_filters( 'image_save_progressive', false, $mime_type ); break; case 'image/avif': - $options['Q'] = $this->get_quality(); - $options['strip'] = $strip_meta; + $options['Q'] = $this->get_quality(); /** * Filters the libvips effort used when encoding AVIF. * @@ -1031,8 +1044,7 @@ protected function get_save_options( $image, $mime_type, $strip_meta = false ) { break; case 'image/webp': - $options['Q'] = $this->get_quality(); - $options['strip'] = $strip_meta; + $options['Q'] = $this->get_quality(); // A lossless WebP has no quality to trade away, so it is re-saved losslessly. if ( $this->lossless ) { @@ -1045,7 +1057,6 @@ protected function get_save_options( $image, $mime_type, $strip_meta = false ) { // editor saves at maximum deflate compression. Deriving a level from the // quality instead wrote files far larger than the source they came from. $options['compression'] = 9; - $options['strip'] = $strip_meta; $options['interlace'] = (bool) apply_filters( 'image_save_progressive', false, $mime_type ); // Asking for a palette back keeps an indexed PNG indexed. Without it the @@ -1057,7 +1068,6 @@ protected function get_save_options( $image, $mime_type, $strip_meta = false ) { break; case 'image/gif': - $options['strip'] = $strip_meta; $options['interlace'] = (bool) apply_filters( 'image_save_progressive', false, $mime_type ); break; } diff --git a/tests/phpunit/tests/image/editorVips.php b/tests/phpunit/tests/image/editorVips.php index 94b07f9da9eaa..b0e33a606cc15 100644 --- a/tests/phpunit/tests/image/editorVips.php +++ b/tests/phpunit/tests/image/editorVips.php @@ -923,8 +923,11 @@ public function test_image_preserves_alpha_on_rotate() { } /** - * Tests that the image_strip_meta filter controls whether metadata is stripped - * when the image is resized. + * Tests that the image_strip_meta filter controls whether a resized image keeps + * all of its metadata. + * + * Reducing metadata keeps the colour profile and the descriptive fields rather than + * dropping every field, which is the set the Imagick editor protects. * * @requires extension exif */ @@ -935,21 +938,24 @@ public function test_image_strip_meta_filter() { return false; }; - // Metadata is stripped by default. + // Descriptive metadata is kept when metadata is reduced. $vips_image_editor = new WP_Image_Editor_Vips( $file ); $vips_image_editor->load(); $this->assertNotWPError( $vips_image_editor->resize( 25, 25 ) ); - $stripped_file = tempnam( get_temp_dir(), 'vips_meta_' ) . '.jpg'; - $vips_image_editor->save( $stripped_file ); + $reduced_file = tempnam( get_temp_dir(), 'vips_meta_' ) . '.jpg'; + $vips_image_editor->save( $reduced_file ); - $stripped = wp_read_image_metadata( $stripped_file ); - unlink( $stripped_file ); + $reduced = wp_read_image_metadata( $reduced_file ); + unlink( $reduced_file ); - $this->assertEmpty( $stripped['caption'], 'Metadata should be stripped by default.' ); + $this->assertNotEmpty( + $reduced['caption'], + 'Descriptive metadata should be kept when metadata is reduced.' + ); - // The filter can prevent stripping. + // The filter can keep everything instead. add_filter( 'image_strip_meta', $strip_meta ); $vips_image_editor = new WP_Image_Editor_Vips( $file ); @@ -968,10 +974,38 @@ public function test_image_strip_meta_filter() { $this->assertNotEmpty( $preserved['caption'], 'Metadata should be preserved when the filter returns false.' ); } + /** + * Tests that a resize keeps the colour profile when it reduces metadata. + * + * Dropping the profile changes how the image renders anywhere nothing converts from + * the original profile, which is why the Imagick editor protects it. + */ + public function test_resizing_keeps_the_color_profile() { + $file = DIR_TESTDATA . '/images/waffles.jpg'; + + $vips_image_editor = new WP_Image_Editor_Vips( $file ); + $vips_image_editor->load(); + + $this->assertNotWPError( $vips_image_editor->resize( 25, 25 ) ); + + $saved_file = tempnam( get_temp_dir(), 'vips_profile_' ) . '.jpg'; + $vips_image_editor->save( $saved_file ); + + // The profile is stored in an APP2 segment tagged ICC_PROFILE. + $saved = file_get_contents( $saved_file ); + unlink( $saved_file ); + + $this->assertStringContainsString( + 'ICC_PROFILE', + $saved, + 'The colour profile should survive a resize that reduces metadata.' + ); + } + /** * Tests that metadata survives a save that does not resize the image. * - * Metadata is only stripped when the image is resized or cropped, matching the + * Metadata is only reduced when the image is resized or cropped, matching the * Imagick editor, so the filter returning true is not enough on its own. * * @requires extension exif From 8c7f69a343d8b83c7673fb32c3f70cdbaf20cac6 Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Wed, 7 Oct 2026 09:04:26 -0600 Subject: [PATCH 72/84] Vips: Remove metadata libvips 8.16 drops but 8.15 keeps The keep mask is only honoured in full from libvips 8.16. On 8.15, PNG text comments, the profiles ImageMagick writes and the image description survive it, so they are removed from the image before it is encoded. The list of fields the mask protects and the list it misses are derived from the same policy, so a field that is protected is never removed. --- .../class-wp-image-editor-vips.php | 47 ++++++++++++ tests/phpunit/tests/image/editorVips.php | 74 +++++++++++++++++++ 2 files changed, 121 insertions(+) diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index eb531ea5f2faa..9aa5f31ca583b 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -903,6 +903,16 @@ protected function _save( $image, $filename = null, $mime_type = null ) { // so saving an image that was merely loaded keeps its metadata. $strip_meta = $strip_meta && $this->resized; + /* + * The `keep` mask is only honoured in full from libvips 8.16. Below that, remove + * what it misses, so that the same fields are dropped on every supported version. + */ + if ( $strip_meta && version_compare( Jcupitt\Vips\Config::version(), '8.16', '<' ) ) { + foreach ( self::get_unprotected_metadata_fields( $image->getFields() ) as $field ) { + $image->remove( $field ); + } + } + $save_options = $this->get_save_options( $image, $mime_type, $strip_meta ); if ( wp_is_stream( $filename ) ) { @@ -1083,6 +1093,43 @@ protected function get_save_options( $image, $mime_type, $strip_meta = false ) { return $options; } + /** + * Returns the metadata fields the `keep` mask fails to drop below libvips 8.16. + * + * The mask is honoured in full from 8.16. Below that, PNG text comments, the profiles + * ImageMagick writes and the image description survive it, as does metadata stored as + * a blob. They are named here so that they can be removed before the image is encoded. + * The fields that hold image structure rather than metadata, such as an animation loop + * count, are not among them and are left to the encoder. + * + * @since 7.2.0 + * + * @param string[] $fields Metadata field names. + * @return string[] Field names to remove. + */ + protected static function get_unprotected_metadata_fields( $fields ) { + // The fields the `keep` mask protects, spelled the way libvips names them. + $protected = array( 'icc-profile-data', 'exif-data', 'iptc-data', 'xmp-data' ); + + $unprotected = array(); + + foreach ( $fields as $field ) { + if ( in_array( $field, $protected, true ) ) { + continue; + } + + if ( '-data' === substr( $field, -5 ) + || 0 === strpos( $field, 'png-comment-' ) + || 0 === strpos( $field, 'magickprofile-' ) + || 'image-description' === $field + ) { + $unprotected[] = $field; + } + } + + return $unprotected; + } + /** * Returns the bit depth to save an image at, honouring `image_max_bit_depth`. * diff --git a/tests/phpunit/tests/image/editorVips.php b/tests/phpunit/tests/image/editorVips.php index b0e33a606cc15..f3fe4b8be54c4 100644 --- a/tests/phpunit/tests/image/editorVips.php +++ b/tests/phpunit/tests/image/editorVips.php @@ -1002,6 +1002,80 @@ public function test_resizing_keeps_the_color_profile() { ); } + /** + * Tests that PNG text comments do not survive a resize that reduces metadata. + * + * libvips only honours the `keep` mask in full from 8.16, and the comments are one of + * the things it misses below that, so they are also removed by hand. + */ + public function test_resizing_drops_png_text_comments() { + $file = DIR_TESTDATA . '/images/transparent.png'; + + $vips_image_editor = new WP_Image_Editor_Vips( $file ); + $vips_image_editor->load(); + + $this->assertNotWPError( $vips_image_editor->resize( 5, 5 ) ); + + $saved_file = tempnam( get_temp_dir(), 'vips_comment_' ) . '.png'; + $vips_image_editor->save( $saved_file ); + + $comments = array_values( + array_filter( + Jcupitt\Vips\Image::newFromFile( $saved_file )->getFields(), + static function ( $field ) { + return 0 === strpos( $field, 'png-comment-' ); + } + ) + ); + unlink( $saved_file ); + + $this->assertSame( + array(), + $comments, + 'PNG text comments should not survive a resize that reduces metadata.' + ); + } + + /** + * Tests which metadata fields have to be removed by hand below libvips 8.16. + * + * The `keep` mask is complete from 8.16, so the code that compensates for it is never + * reached on a newer libvips and cannot be exercised through the editor. The list it + * relies on is checked directly instead. + */ + public function test_unprotected_metadata_fields() { + $method = new ReflectionMethod( 'WP_Image_Editor_Vips', 'get_unprotected_metadata_fields' ); + $method->setAccessible( true ); + + $fields = array( + // Protected by the `keep` mask. + 'icc-profile-data', + 'exif-data', + 'iptc-data', + 'xmp-data', + // Not protected. + 'jpeg-thumbnail-data', + 'png-comment-1-Software', + 'magickprofile-foo', + 'image-description', + // Not metadata at all. + 'width', + 'orientation', + 'loop', + 'n-pages', + ); + + $this->assertSame( + array( + 'jpeg-thumbnail-data', + 'png-comment-1-Software', + 'magickprofile-foo', + 'image-description', + ), + $method->invoke( null, $fields ) + ); + } + /** * Tests that metadata survives a save that does not resize the image. * From cc571ea783cb5f68acb26318d384be10619409dd Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Wed, 7 Oct 2026 09:12:13 -0600 Subject: [PATCH 73/84] Vips: Reference the image_save_progressive filter documentation The filter is documented on the GD editor, which is where the Imagick editor points as well, and core's own static analysis requires each call site to say so. --- src/wp-includes/class-wp-image-editor-vips.php | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index 9aa5f31ca583b..119ca7846bddb 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -1035,7 +1035,9 @@ protected function get_save_options( $image, $mime_type, $strip_meta = false ) { case 'image/jpeg': $options['Q'] = $this->get_quality(); $options['optimize_coding'] = true; - $options['interlace'] = (bool) apply_filters( 'image_save_progressive', false, $mime_type ); + + /** This filter is documented in wp-includes/class-wp-image-editor-gd.php */ + $options['interlace'] = (bool) apply_filters( 'image_save_progressive', false, $mime_type ); break; case 'image/avif': @@ -1067,7 +1069,9 @@ protected function get_save_options( $image, $mime_type, $strip_meta = false ) { // editor saves at maximum deflate compression. Deriving a level from the // quality instead wrote files far larger than the source they came from. $options['compression'] = 9; - $options['interlace'] = (bool) apply_filters( 'image_save_progressive', false, $mime_type ); + + /** This filter is documented in wp-includes/class-wp-image-editor-gd.php */ + $options['interlace'] = (bool) apply_filters( 'image_save_progressive', false, $mime_type ); // Asking for a palette back keeps an indexed PNG indexed. Without it the // resized image is written as true colour, which is much larger than the @@ -1078,6 +1082,7 @@ protected function get_save_options( $image, $mime_type, $strip_meta = false ) { break; case 'image/gif': + /** This filter is documented in wp-includes/class-wp-image-editor-gd.php */ $options['interlace'] = (bool) apply_filters( 'image_save_progressive', false, $mime_type ); break; } From efe53ee3e436903fb0beadd6755720f6e6995eed Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Wed, 7 Oct 2026 09:22:59 -0600 Subject: [PATCH 74/84] Vips: Test that truncated images are rejected The loader is asked to fail on truncation, but libvips reads pixels lazily, so a truncated PNG is rejected at load by some encoders and only when the pixels are first read by others. The test asserts the contract that holds either way: a truncated file produces no output. A truncated JPEG is still filled rather than rejected, matching the GD and Imagick editors. --- tests/phpunit/tests/image/editorVips.php | 63 ++++++++++++++++++++++++ 1 file changed, 63 insertions(+) diff --git a/tests/phpunit/tests/image/editorVips.php b/tests/phpunit/tests/image/editorVips.php index f3fe4b8be54c4..2efa52833fb05 100644 --- a/tests/phpunit/tests/image/editorVips.php +++ b/tests/phpunit/tests/image/editorVips.php @@ -719,6 +719,69 @@ public function test_flip() { $this->assertSame( $expected['blue'], $actual['blue'] ); } + /** + * Tests that a truncated image is not saved. + * + * The editor asks the loader to fail on truncation, but libvips reads pixels lazily, + * so an encoder that detects the damage from the header rejects the file at load and + * one that does not only reports it when the pixels are first read. Whichever happens, + * a truncated file must not produce output. + */ + public function test_truncated_images_are_not_saved() { + $data = file_get_contents( DIR_TESTDATA . '/images/transparent.png' ); + + $file = tempnam( get_temp_dir(), 'vips_truncated_' ) . '.png'; + file_put_contents( $file, substr( $data, 0, (int) ( strlen( $data ) * 0.6 ) ) ); + + $saved_file = tempnam( get_temp_dir(), 'vips_truncated_out_' ) . '.png'; + + $vips_image_editor = new WP_Image_Editor_Vips( $file ); + $saved = false; + + if ( ! is_wp_error( $vips_image_editor->load() ) ) { + $vips_image_editor->resize( 5, 5 ); + + $saved = ! is_wp_error( $vips_image_editor->save( $saved_file ) ); + } + + unlink( $file ); + + if ( file_exists( $saved_file ) ) { + unlink( $saved_file ); + } + + $this->assertFalse( $saved, 'A truncated image should not be saved.' ); + } + + /** + * Tests that a truncated JPEG is filled in rather than rejected. + * + * JPEG is the exception to the truncation check because damage in one is + * recoverable, and the GD and Imagick editors fill it and carry on. + */ + public function test_truncated_jpeg_is_filled_rather_than_rejected() { + $data = file_get_contents( DIR_TESTDATA . '/images/waffles.jpg' ); + + $file = tempnam( get_temp_dir(), 'vips_truncated_jpeg_' ) . '.jpg'; + file_put_contents( $file, substr( $data, 0, (int) ( strlen( $data ) * 0.6 ) ) ); + + $vips_image_editor = new WP_Image_Editor_Vips( $file ); + + $this->assertNotWPError( $vips_image_editor->load() ); + $this->assertNotWPError( $vips_image_editor->resize( 5, 5 ) ); + + $saved_file = tempnam( get_temp_dir(), 'vips_truncated_jpeg_out_' ) . '.jpg'; + $saved = $vips_image_editor->save( $saved_file ); + + unlink( $file ); + + if ( file_exists( $saved_file ) ) { + unlink( $saved_file ); + } + + $this->assertNotWPError( $saved ); + } + /** * Tests that WP_Image_Editor_Vips handles extensionless images. * From 5063bc5932794e823f74e1f24f1cb1d78c69a3c5 Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Wed, 7 Oct 2026 09:24:33 -0600 Subject: [PATCH 75/84] Vips: Test saving as AVIF The AVIF path was only covered by loading one and saving it as PNG. This saves as AVIF, checks the file really is one, and checks that the encoding effort defaults to 3 and that the filter is what the encoder is given. --- tests/phpunit/tests/image/editorVips.php | 62 ++++++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/tests/phpunit/tests/image/editorVips.php b/tests/phpunit/tests/image/editorVips.php index 2efa52833fb05..16cf3ebb8edbf 100644 --- a/tests/phpunit/tests/image/editorVips.php +++ b/tests/phpunit/tests/image/editorVips.php @@ -1437,4 +1437,66 @@ static function () { unlink( $temp_tmp ); unlink( $saved['path'] ); } + + /** + * Tests that an image is saved as AVIF, and that the encoding effort is filterable. + * + * The effort is what the encoder trades time for quality with, and its default is + * low enough to stay inside a typical PHP-FPM request limit. + */ + public function test_saving_as_avif() { + if ( ! WP_Image_Editor_Vips::supports_mime_type( 'image/avif' ) ) { + $this->markTestSkipped( 'The image editor does not support the AVIF mime type.' ); + } + + $file = DIR_TESTDATA . '/images/waffles.jpg'; + + $effort = null; + $record = static function ( $value ) use ( &$effort ) { + $effort = $value; + + return $value; + }; + + add_filter( 'wp_image_editor_vips_avif_effort', $record ); + + $vips_image_editor = new WP_Image_Editor_Vips( $file ); + $vips_image_editor->load(); + + $this->assertNotWPError( $vips_image_editor->resize( 50, 50 ) ); + + $saved_file = tempnam( get_temp_dir(), 'vips_avif_' ) . '.avif'; + $saved = $vips_image_editor->save( $saved_file, 'image/avif' ); + + // An AVIF file is a box structure, and its first box type is `ftypavif`. + $magic = substr( file_get_contents( $saved_file ), 4, 8 ); + unlink( $saved_file ); + + remove_filter( 'wp_image_editor_vips_avif_effort', $record ); + + $this->assertNotWPError( $saved ); + $this->assertSame( 'image/avif', $saved['mime-type'] ); + $this->assertSame( 3, $effort, 'The encoding effort should default to 3.' ); + $this->assertSame( 'ftypavif', $magic, 'The saved file should be an AVIF image.' ); + + // A filtered effort is what the encoder is given. + add_filter( + 'wp_image_editor_vips_avif_effort', + static function () { + return 1; + } + ); + + $vips_image_editor = new WP_Image_Editor_Vips( $file ); + $vips_image_editor->load(); + + $this->assertNotWPError( $vips_image_editor->resize( 50, 50 ) ); + + $saved_file = tempnam( get_temp_dir(), 'vips_avif_' ) . '.avif'; + $filtered = $vips_image_editor->save( $saved_file, 'image/avif' ); + + unlink( $saved_file ); + + $this->assertNotWPError( $filtered ); + } } From 4c465b775b6c84702be1142ce244e9d34fffd6fb Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Wed, 7 Oct 2026 09:27:36 -0600 Subject: [PATCH 76/84] Vips: Test that rotating moves the pixels The existing test rotated a square image 180 degrees and only checked that the size was unchanged, so a rotation that did nothing would have passed. This rotates a non-square image through every right angle and compares each corner of the result with the corner of the source it should have come from, which also covers the dimension swap a quarter turn has to make. --- tests/phpunit/tests/image/editorVips.php | 146 +++++++++++++++++++++-- 1 file changed, 136 insertions(+), 10 deletions(-) diff --git a/tests/phpunit/tests/image/editorVips.php b/tests/phpunit/tests/image/editorVips.php index 16cf3ebb8edbf..ed9b5284d4bec 100644 --- a/tests/phpunit/tests/image/editorVips.php +++ b/tests/phpunit/tests/image/editorVips.php @@ -621,26 +621,152 @@ public function data_crop_invalid_dimensions() { } /** - * Tests rotating an image 180 deg. + * Tests that rotating moves the pixels and not just the dimensions. + * + * Each right angle is an exact move of whole pixels, so every corner of the result is + * compared with the corner of the source it should have come from. The source corners + * are read from a lossless copy, so the comparison does not depend on the JPEG being + * decoded the same way twice. + * + * @dataProvider data_rotation_angles + * + * @param float $angle Angle in degrees, counter-clockwise. + * @param array $corners Map of result corner to source corner. + * @param array $expected_size Expected width and height after rotating. */ - public function test_rotate() { - $file = DIR_TESTDATA . '/images/gradient-square.jpg'; + public function test_rotate( $angle, $corners, $expected_size ) { + $file = DIR_TESTDATA . '/images/sugarloaf-mountain.jpg'; + + $original_editor = new WP_Image_Editor_Vips( $file ); + $original_editor->load(); + + $original_tmp = tempnam( get_temp_dir(), 'vips_rotate_' ); + $original_file = $original_tmp . '.png'; + $original_editor->save( $original_file ); $vips_image_editor = new WP_Image_Editor_Vips( $file ); $vips_image_editor->load(); - $result = $vips_image_editor->rotate( 180 ); + $this->assertTrue( $vips_image_editor->rotate( $angle ) ); - $this->assertTrue( $result ); - $this->assertSame( - array( - 'width' => 100, - 'height' => 100, + $rotated_tmp = tempnam( get_temp_dir(), 'vips_rotate_' ); + $rotated_file = $rotated_tmp . '.png'; + $vips_image_editor->save( $rotated_file ); + + $original = $this->get_corner_pixels( $original_file ); + $rotated = $this->get_corner_pixels( $rotated_file ); + $size = $vips_image_editor->get_size(); + + unlink( $original_tmp ); + unlink( $original_file ); + unlink( $rotated_tmp ); + unlink( $rotated_file ); + + foreach ( $corners as $corner => $source ) { + $this->assertSame( + $original[ $source ], + $rotated[ $corner ], + "Rotating {$angle} degrees should move the {$source} corner to the {$corner} corner." + ); + } + + $this->assertSame( $expected_size, $size ); + } + + /** + * Data provider for test_rotate. + * + * The source is 300x169, so a quarter turn has to change the dimensions as well as + * move the pixels. + * + * @return array,2:array}> + */ + public static function data_rotation_angles() { + return array( + '90 degrees counter-clockwise' => array( + 90, + array( + 'TL' => 'TR', + 'TR' => 'BR', + 'BR' => 'BL', + 'BL' => 'TL', + ), + array( + 'width' => 169, + 'height' => 300, + ), + ), + '180 degrees' => array( + 180, + array( + 'TL' => 'BR', + 'TR' => 'BL', + 'BR' => 'TL', + 'BL' => 'TR', + ), + array( + 'width' => 300, + 'height' => 169, + ), + ), + '270 degrees counter-clockwise' => array( + 270, + array( + 'TL' => 'BL', + 'TR' => 'TL', + 'BR' => 'TR', + 'BL' => 'BR', + ), + array( + 'width' => 169, + 'height' => 300, + ), + ), + 'negative quarter turn' => array( + -90, + array( + 'TL' => 'BL', + 'TR' => 'TL', + 'BR' => 'TR', + 'BL' => 'BR', + ), + array( + 'width' => 169, + 'height' => 300, + ), ), - $vips_image_editor->get_size() ); } + /** + * Returns the four corner pixels of a PNG, keyed by corner. + * + * @param string $file Path to a PNG file. + * @return array Corner pixels as `red,green,blue`. + */ + private function get_corner_pixels( $file ) { + $image = imagecreatefrompng( $file ); + $width = imagesx( $image ); + $height = imagesy( $image ); + + $pixel = static function ( $x, $y ) use ( $image ) { + $colour = imagecolorsforindex( $image, imagecolorat( $image, $x, $y ) ); + + return $colour['red'] . ',' . $colour['green'] . ',' . $colour['blue']; + }; + + $corners = array( + 'TL' => $pixel( 0, 0 ), + 'TR' => $pixel( $width - 1, 0 ), + 'BR' => $pixel( $width - 1, $height - 1 ), + 'BL' => $pixel( 0, $height - 1 ), + ); + + imagedestroy( $image ); + + return $corners; + } + /** * Tests resetting Exif orientation data on rotate. * From a978d041437815aa830f60a91980a87e6151a252 Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Wed, 7 Oct 2026 09:28:44 -0600 Subject: [PATCH 77/84] Vips: Test both flip axes Only the horizontal axis was covered, and only by one corner. This checks both axes by comparing every corner with the corner it should have come from, on a fixture whose four corners are all different, so a flip on the wrong axis cannot pass. --- tests/phpunit/tests/image/editorVips.php | 71 ++++++++++++++++++------ 1 file changed, 53 insertions(+), 18 deletions(-) diff --git a/tests/phpunit/tests/image/editorVips.php b/tests/phpunit/tests/image/editorVips.php index ed9b5284d4bec..9bf17743d3bb5 100644 --- a/tests/phpunit/tests/image/editorVips.php +++ b/tests/phpunit/tests/image/editorVips.php @@ -801,16 +801,25 @@ public function test_remove_orientation_data_on_rotate() { } /** - * Tests that flipping along the horizontal axis mirrors the image vertically. + * Tests that flipping mirrors the image on the axis it was asked for. + * + * Flipping along the horizontal axis mirrors the image top to bottom, and along the + * vertical axis left to right. Every corner is compared with the corner it should have + * come from, on a fixture whose four corners are all different. + * + * @dataProvider data_flip_axes + * + * @param bool $horz Whether to flip along the horizontal axis. + * @param bool $vert Whether to flip along the vertical axis. + * @param array $corners Map of result corner to source corner. */ - public function test_flip() { - $file = DIR_TESTDATA . '/images/gradient-square.jpg'; + public function test_flip( $horz, $vert, $corners ) { + $file = DIR_TESTDATA . '/images/sugarloaf-mountain.jpg'; // Save a lossless copy of the unmodified image to sample the source pixels from. $original_editor = new WP_Image_Editor_Vips( $file ); $original_editor->load(); - $size = $original_editor->get_size(); $original_tmp = tempnam( get_temp_dir(), 'vips_flip_' ); $original_file = $original_tmp . '.png'; $original_editor->save( $original_file ); @@ -818,31 +827,57 @@ public function test_flip() { $vips_image_editor = new WP_Image_Editor_Vips( $file ); $vips_image_editor->load(); - $flipped = $vips_image_editor->flip( true, false ); - $this->assertTrue( $flipped ); + $this->assertTrue( $vips_image_editor->flip( $horz, $vert ) ); $flipped_tmp = tempnam( get_temp_dir(), 'vips_flip_' ); $flipped_file = $flipped_tmp . '.png'; $vips_image_editor->save( $flipped_file ); - $original_image = imagecreatefrompng( $original_file ); - $flipped_image = imagecreatefrompng( $flipped_file ); - - // Flipping along the horizontal axis moves the bottom-left pixel to the top-left. - $expected = imagecolorsforindex( $original_image, imagecolorat( $original_image, 0, $size['height'] - 1 ) ); - $actual = imagecolorsforindex( $flipped_image, imagecolorat( $flipped_image, 0, 0 ) ); - - imagedestroy( $original_image ); - imagedestroy( $flipped_image ); + $original = $this->get_corner_pixels( $original_file ); + $flipped = $this->get_corner_pixels( $flipped_file ); unlink( $original_tmp ); unlink( $original_file ); unlink( $flipped_tmp ); unlink( $flipped_file ); - $this->assertSame( $expected['red'], $actual['red'] ); - $this->assertSame( $expected['green'], $actual['green'] ); - $this->assertSame( $expected['blue'], $actual['blue'] ); + foreach ( $corners as $corner => $source ) { + $this->assertSame( + $original[ $source ], + $flipped[ $corner ], + "Flipping should move the {$source} corner to the {$corner} corner." + ); + } + } + + /** + * Data provider for test_flip. + * + * @return array}> + */ + public static function data_flip_axes() { + return array( + 'along the horizontal axis' => array( + true, + false, + array( + 'TL' => 'BL', + 'TR' => 'BR', + 'BR' => 'TR', + 'BL' => 'TL', + ), + ), + 'along the vertical axis' => array( + false, + true, + array( + 'TL' => 'TR', + 'TR' => 'TL', + 'BR' => 'BL', + 'BL' => 'BR', + ), + ), + ); } /** From c450076822107beecfa085268b81d274f4c025d8 Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Wed, 7 Oct 2026 09:32:16 -0600 Subject: [PATCH 78/84] Vips: Test the minimum libvips version The floor decides whether the editor is used at all, but reaching it through test() needs an older libvips than the one running the suite, so the comparison moves into its own method and is checked directly: 8.7, 8.12.1 and 8.14.5 are rejected, 8.15 and above are accepted. --- .../class-wp-image-editor-vips.php | 24 +++++++++---- tests/phpunit/tests/image/editorVips.php | 35 +++++++++++++++++++ 2 files changed, 52 insertions(+), 7 deletions(-) diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index 119ca7846bddb..74bc51adcb2c6 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -118,13 +118,7 @@ public static function test( $args = array() ) { // Try to get the libvips version to confirm it's working. try { $version = Jcupitt\Vips\Config::version(); - if ( empty( $version ) ) { - return false; - } - - // Require libvips 8.15 or later, which is the first version with the `keep` - // saver option used to preserve colour profiles when metadata is stripped. - if ( version_compare( $version, '8.15', '<' ) ) { + if ( empty( $version ) || ! self::is_supported_version( $version ) ) { return false; } } catch ( Exception $e ) { @@ -136,6 +130,22 @@ public static function test( $args = array() ) { return true; } + /** + * Checks whether a libvips version is new enough for this editor. + * + * 8.15 is the first version with the `keep` saver option, which is what preserves the + * colour profile when metadata is reduced. Below it the editor reports itself + * unsupported, and image editing falls back to Imagick or GD. + * + * @since 7.2.0 + * + * @param string $version A libvips version, as `Config::version()` reports it. + * @return bool + */ + protected static function is_supported_version( $version ) { + return version_compare( $version, '8.15', '>=' ); + } + /** * Processes the libvips loaders that may be used to decode an image. * diff --git a/tests/phpunit/tests/image/editorVips.php b/tests/phpunit/tests/image/editorVips.php index 9bf17743d3bb5..daa8f01e3da82 100644 --- a/tests/phpunit/tests/image/editorVips.php +++ b/tests/phpunit/tests/image/editorVips.php @@ -943,6 +943,41 @@ public function test_truncated_jpeg_is_filled_rather_than_rejected() { $this->assertNotWPError( $saved ); } + /** + * Tests which libvips versions the editor accepts. + * + * The floor is what decides whether the editor is used at all, and reaching it through + * test() would need an older libvips than the one running the suite, so the comparison + * is checked directly. + * + * @dataProvider data_libvips_versions + * + * @param string $version A libvips version. + * @param bool $expected Whether the editor should accept it. + */ + public function test_supported_libvips_versions( $version, $expected ) { + $method = new ReflectionMethod( 'WP_Image_Editor_Vips', 'is_supported_version' ); + $method->setAccessible( true ); + + $this->assertSame( $expected, $method->invoke( null, $version ) ); + } + + /** + * Data provider for test_supported_libvips_versions. + * + * @return array + */ + public static function data_libvips_versions() { + return array( + array( '8.7', false ), + array( '8.12.1', false ), + array( '8.14.5', false ), + array( '8.15', true ), + array( '8.15.1', true ), + array( '8.16.1', true ), + ); + } + /** * Tests that WP_Image_Editor_Vips handles extensionless images. * From 908df801ba206e07a9d178823aeb6bcd95f159e4 Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Wed, 7 Oct 2026 09:55:46 -0600 Subject: [PATCH 79/84] Vips: Support libvips 8.13, using the `keep` mask only where it exists The `keep` saver option that preserves the colour profile when metadata is reduced only exists from libvips 8.15, and passing an unknown option fails the save. Move the floor to 8.13 and pass `keep` only where it exists; below that the fields are removed by hand, which was already happening below 8.16. Restore the libvips 8.14 guard on the GIF interlace option, which the 8.15 floor had made unnecessary. --- .../class-wp-image-editor-vips.php | 41 +++++++++++++++---- tests/phpunit/tests/image/editorVips.php | 36 +++++++++++++++- 2 files changed, 67 insertions(+), 10 deletions(-) diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index 74bc51adcb2c6..c8c5b4bc6d235 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -133,9 +133,9 @@ public static function test( $args = array() ) { /** * Checks whether a libvips version is new enough for this editor. * - * 8.15 is the first version with the `keep` saver option, which is what preserves the - * colour profile when metadata is reduced. Below it the editor reports itself - * unsupported, and image editing falls back to Imagick or GD. + * 8.13 is the floor: it is the first version that can write a palette back to a PNG, + * which is what keeps a resized indexed PNG from ballooning. Below it the editor reports + * itself unsupported, and image editing falls back to Imagick or GD. * * @since 7.2.0 * @@ -143,6 +143,23 @@ public static function test( $args = array() ) { * @return bool */ protected static function is_supported_version( $version ) { + return version_compare( $version, '8.13', '>=' ); + } + + /** + * Checks whether a libvips version can reduce metadata with the `keep` mask. + * + * The mask is what preserves the colour profile while dropping the rest, so the editor + * prefers it where it exists. It arrived in 8.15, and is honoured in full from 8.16. + * Below 8.15 the option does not exist, and passing it would fail the save, so the + * unwanted fields are removed by hand instead. + * + * @since 7.2.0 + * + * @param string $version A libvips version, as `Config::version()` reports it. + * @return bool + */ + protected static function uses_keep_option( $version ) { return version_compare( $version, '8.15', '>=' ); } @@ -914,8 +931,10 @@ protected function _save( $image, $filename = null, $mime_type = null ) { $strip_meta = $strip_meta && $this->resized; /* - * The `keep` mask is only honoured in full from libvips 8.16. Below that, remove - * what it misses, so that the same fields are dropped on every supported version. + * Remove the fields the `keep` mask would have dropped. The mask is only honoured in + * full from libvips 8.16, and does not exist below 8.15, so on those versions this is + * what reduces the metadata. Removing the fields here means the same ones are dropped + * whatever the mask can do. */ if ( $strip_meta && version_compare( Jcupitt\Vips\Config::version(), '8.16', '<' ) ) { foreach ( self::get_unprotected_metadata_fields( $image->getFields() ) as $field ) { @@ -1033,8 +1052,11 @@ protected function get_save_options( $image, $mime_type, $strip_meta = false ) { * image renders once nothing tells the browser how to interpret the samples. The * `keep` mask drops the rest while preserving the colour profile and the descriptive * fields, which is the set the Imagick editor keeps. + * + * The mask only exists from libvips 8.15. Below that the caller has already removed the + * fields it would have dropped, so no other option is needed here. */ - if ( $strip_meta ) { + if ( $strip_meta && self::uses_keep_option( Jcupitt\Vips\Config::version() ) ) { $options['keep'] = Jcupitt\Vips\ForeignKeep::ICC | Jcupitt\Vips\ForeignKeep::EXIF | Jcupitt\Vips\ForeignKeep::XMP @@ -1092,8 +1114,11 @@ protected function get_save_options( $image, $mime_type, $strip_meta = false ) { break; case 'image/gif': - /** This filter is documented in wp-includes/class-wp-image-editor-gd.php */ - $options['interlace'] = (bool) apply_filters( 'image_save_progressive', false, $mime_type ); + // gifsave gained the interlace option in libvips 8.14. + if ( version_compare( Jcupitt\Vips\Config::version(), '8.14', '>=' ) ) { + /** This filter is documented in wp-includes/class-wp-image-editor-gd.php */ + $options['interlace'] = (bool) apply_filters( 'image_save_progressive', false, $mime_type ); + } break; } diff --git a/tests/phpunit/tests/image/editorVips.php b/tests/phpunit/tests/image/editorVips.php index daa8f01e3da82..d626788b05bd1 100644 --- a/tests/phpunit/tests/image/editorVips.php +++ b/tests/phpunit/tests/image/editorVips.php @@ -971,13 +971,45 @@ public static function data_libvips_versions() { return array( array( '8.7', false ), array( '8.12.1', false ), - array( '8.14.5', false ), - array( '8.15', true ), + array( '8.13', true ), + array( '8.14.1', true ), array( '8.15.1', true ), array( '8.16.1', true ), ); } + /** + * Tests which libvips versions can reduce metadata with the `keep` mask. + * + * The option does not exist below 8.15, and passing it would fail the save, so this + * comparison is what decides whether it can be used. + * + * @dataProvider data_libvips_keep_support + * + * @param string $version A libvips version. + * @param bool $expected Whether the `keep` option can be used. + */ + public function test_uses_keep_option( $version, $expected ) { + $method = new ReflectionMethod( 'WP_Image_Editor_Vips', 'uses_keep_option' ); + $method->setAccessible( true ); + + $this->assertSame( $expected, $method->invoke( null, $version ) ); + } + + /** + * Data provider for test_uses_keep_option. + * + * @return array + */ + public static function data_libvips_keep_support() { + return array( + array( '8.13', false ), + array( '8.14.1', false ), + array( '8.15', true ), + array( '8.16.1', true ), + ); + } + /** * Tests that WP_Image_Editor_Vips handles extensionless images. * From 77053b8df16dcef77503bf9c053dc1bb04bd6bf7 Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Wed, 7 Oct 2026 12:18:39 -0600 Subject: [PATCH 80/84] Vips: Decide the metadata reduction in one place Whether the `keep` mask can be passed, and whether the unprotected fields also have to be removed by hand, were answered by two separate version checks: one in _save(), one in get_save_options() while building the saver options. get_metadata_strategy() now returns both answers for a version, so the policy lives in one place. get_save_options() takes that strategy instead of a strip_meta boolean, and _save() consults it for the removal. --- .../class-wp-image-editor-vips.php | 62 +++++++++++-------- tests/phpunit/tests/image/editorVips.php | 41 +++++++----- 2 files changed, 62 insertions(+), 41 deletions(-) diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index c8c5b4bc6d235..5ccad8f3c572e 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -147,20 +147,31 @@ protected static function is_supported_version( $version ) { } /** - * Checks whether a libvips version can reduce metadata with the `keep` mask. + * Returns how a libvips version reduces an image's metadata. * - * The mask is what preserves the colour profile while dropping the rest, so the editor - * prefers it where it exists. It arrived in 8.15, and is honoured in full from 8.16. - * Below 8.15 the option does not exist, and passing it would fail the save, so the - * unwanted fields are removed by hand instead. + * Reducing metadata means keeping the colour profile and the descriptive fields, and + * dropping the rest, which is the set the Imagick editor keeps. libvips offers two ways + * to do it, and which are available depends on the version: + * + * - The `keep` mask names the fields to hold on to and drops everything else. It exists + * from 8.15, and drops everything it should from 8.16. Passing it to an older libvips + * fails the save, so it can only be used where it exists. + * - Removing the fields by hand works on every version, but has to name them. + * + * 8.15 needs both: the mask does most of the work, and the removal covers the fields it + * misses. 8.13 and 8.14 have no mask at all, so the removal does all of it. * * @since 7.2.0 * * @param string $version A libvips version, as `Config::version()` reports it. - * @return bool + * @return array{keep:bool,remove:bool} Whether the `keep` mask can be passed, and whether + * the unprotected fields have to be removed by hand. */ - protected static function uses_keep_option( $version ) { - return version_compare( $version, '8.15', '>=' ); + protected static function get_metadata_strategy( $version ) { + return array( + 'keep' => version_compare( $version, '8.15', '>=' ), + 'remove' => version_compare( $version, '8.16', '<' ), + ); } /** @@ -931,18 +942,20 @@ protected function _save( $image, $filename = null, $mime_type = null ) { $strip_meta = $strip_meta && $this->resized; /* - * Remove the fields the `keep` mask would have dropped. The mask is only honoured in - * full from libvips 8.16, and does not exist below 8.15, so on those versions this is - * what reduces the metadata. Removing the fields here means the same ones are dropped - * whatever the mask can do. + * The metadata is only reduced on a resized save, and how it is reduced depends on the + * libvips version. See get_metadata_strategy(). */ - if ( $strip_meta && version_compare( Jcupitt\Vips\Config::version(), '8.16', '<' ) ) { + $metadata_strategy = $strip_meta + ? self::get_metadata_strategy( Jcupitt\Vips\Config::version() ) + : array(); + + if ( ! empty( $metadata_strategy['remove'] ) ) { foreach ( self::get_unprotected_metadata_fields( $image->getFields() ) as $field ) { $image->remove( $field ); } } - $save_options = $this->get_save_options( $image, $mime_type, $strip_meta ); + $save_options = $this->get_save_options( $image, $mime_type, $metadata_strategy ); if ( wp_is_stream( $filename ) ) { $buffer = $image->writeToBuffer( '.' . $extension, $save_options ); @@ -1036,14 +1049,15 @@ public function stream( $mime_type = null ) { * * @since 7.2.0 * - * @param Jcupitt\Vips\Image $image The image being written. - * @param string $mime_type The mime type it is being written as. - * @param bool $strip_meta Optional. Whether to reduce the metadata to the - * colour profile and the descriptive fields. - * Default false. + * @param Jcupitt\Vips\Image $image The image being written. + * @param string $mime_type The mime type it is being written as. + * @param array $metadata_strategy Optional. The strategy from + * get_metadata_strategy(), or an empty + * array to write the metadata unchanged. + * Default empty. * @return array Options passed to `writeToBuffer()` or `writeToFile()`. */ - protected function get_save_options( $image, $mime_type, $strip_meta = false ) { + protected function get_save_options( $image, $mime_type, $metadata_strategy = array() ) { $options = array(); /* @@ -1051,12 +1065,10 @@ protected function get_save_options( $image, $mime_type, $strip_meta = false ) { * boolean drops every field, including the colour profile, which changes how the * image renders once nothing tells the browser how to interpret the samples. The * `keep` mask drops the rest while preserving the colour profile and the descriptive - * fields, which is the set the Imagick editor keeps. - * - * The mask only exists from libvips 8.15. Below that the caller has already removed the - * fields it would have dropped, so no other option is needed here. + * fields, which is the set the Imagick editor keeps, and is passed when + * get_metadata_strategy() says the version supports it. */ - if ( $strip_meta && self::uses_keep_option( Jcupitt\Vips\Config::version() ) ) { + if ( ! empty( $metadata_strategy['keep'] ) ) { $options['keep'] = Jcupitt\Vips\ForeignKeep::ICC | Jcupitt\Vips\ForeignKeep::EXIF | Jcupitt\Vips\ForeignKeep::XMP diff --git a/tests/phpunit/tests/image/editorVips.php b/tests/phpunit/tests/image/editorVips.php index d626788b05bd1..c74df4c7d70f1 100644 --- a/tests/phpunit/tests/image/editorVips.php +++ b/tests/phpunit/tests/image/editorVips.php @@ -979,34 +979,43 @@ public static function data_libvips_versions() { } /** - * Tests which libvips versions can reduce metadata with the `keep` mask. + * Tests how each libvips version reduces an image's metadata. * - * The option does not exist below 8.15, and passing it would fail the save, so this - * comparison is what decides whether it can be used. + * `keep` says whether the `keep` mask can be passed, and `remove` whether the fields + * also have to be removed by hand. The mask exists from 8.15 and is complete from + * 8.16, so 8.15 needs both. * - * @dataProvider data_libvips_keep_support + * @dataProvider data_libvips_metadata_strategy * - * @param string $version A libvips version. - * @param bool $expected Whether the `keep` option can be used. + * @param string $version A libvips version. + * @param bool $keep Whether the `keep` mask can be passed. + * @param bool $remove Whether the unprotected fields have to be removed by hand. */ - public function test_uses_keep_option( $version, $expected ) { - $method = new ReflectionMethod( 'WP_Image_Editor_Vips', 'uses_keep_option' ); + public function test_metadata_strategy( $version, $keep, $remove ) { + $method = new ReflectionMethod( 'WP_Image_Editor_Vips', 'get_metadata_strategy' ); $method->setAccessible( true ); - $this->assertSame( $expected, $method->invoke( null, $version ) ); + $this->assertSame( + array( + 'keep' => $keep, + 'remove' => $remove, + ), + $method->invoke( null, $version ) + ); } /** - * Data provider for test_uses_keep_option. + * Data provider for test_metadata_strategy. * - * @return array + * @return array */ - public static function data_libvips_keep_support() { + public static function data_libvips_metadata_strategy() { return array( - array( '8.13', false ), - array( '8.14.1', false ), - array( '8.15', true ), - array( '8.16.1', true ), + array( '8.13', false, true ), + array( '8.14.1', false, true ), + array( '8.15', true, true ), + array( '8.16', true, false ), + array( '8.16.1', true, false ), ); } From f3e49a21af3c3ae4ce7118b2a55fab1f85d0dac4 Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Wed, 7 Oct 2026 13:06:15 -0600 Subject: [PATCH 81/84] Vips: Test that resizing an animated GIF saves one frame --- tests/phpunit/data/images/gif-animated.gif | Bin 0 -> 279 bytes tests/phpunit/tests/image/editorVips.php | 113 +++++++++++++++++++++ 2 files changed, 113 insertions(+) create mode 100644 tests/phpunit/data/images/gif-animated.gif diff --git a/tests/phpunit/data/images/gif-animated.gif b/tests/phpunit/data/images/gif-animated.gif new file mode 100644 index 0000000000000000000000000000000000000000..9b17b37fa8fdc1021ab2357596719f56cc255232 GIT binary patch literal 279 zcmZ?wbhEHbOkwb5_`tyMp8*6E|8x7fh6Fo12DlpO889<~gnqJcZ~ulEcJL|r4^K~D8vgv1!-|Fjcw*BVqKmGj6uD^ZfUw{AeZyy#* L8z3&EgVojm@2QM= literal 0 HcmV?d00001 diff --git a/tests/phpunit/tests/image/editorVips.php b/tests/phpunit/tests/image/editorVips.php index c74df4c7d70f1..dc08f613fbe67 100644 --- a/tests/phpunit/tests/image/editorVips.php +++ b/tests/phpunit/tests/image/editorVips.php @@ -1222,6 +1222,46 @@ public function test_image_preserves_alpha_on_rotate() { unlink( $save_to_file ); } + /** + * Tests that resizing an animated GIF saves a single frame. + * + * Core flattens animated GIFs into one frame when generating intermediate sizes, + * and WP_Image_Editor_Imagick::load() selects the first frame to match. The Vips + * editor has to do the same: load the first frame rather than every frame, and + * never write an animation back. + */ + public function test_resizing_an_animated_gif_saves_a_single_frame() { + $file = DIR_TESTDATA . '/images/gif-animated.gif'; + + $this->assertSame( 2, $this->count_gif_frames( $file ), 'The fixture should be a two-frame GIF.' ); + + $vips_image_editor = new WP_Image_Editor_Vips( $file ); + $vips_image_editor->load(); + + $this->assertSame( + array( + 'width' => 100, + 'height' => 75, + ), + $vips_image_editor->get_size(), + 'The editor should load the first frame, not every frame stacked.' + ); + + $vips_image_editor->resize( 50, 50 ); + + $save_to_file = tempnam( get_temp_dir(), '' ) . '.gif'; + + $vips_image_editor->save( $save_to_file ); + + $this->assertSame( + 1, + $this->count_gif_frames( $save_to_file ), + 'Saving a resized GIF should not write an animation.' + ); + + unlink( $save_to_file ); + } + /** * Tests that the image_strip_meta filter controls whether a resized image keeps * all of its metadata. @@ -1493,6 +1533,79 @@ private function is_lossless_webp( $contents ) { return false !== strpos( $contents, 'VP8L' ); } + /** + * Counts the frames in a GIF by walking its block structure. + * + * Each frame is introduced by an image descriptor, so counting those counts frames + * without relying on the image library that wrote the file. + * + * @param string $file Path to a GIF file. + * @return int The number of frames. + */ + private function count_gif_frames( $file ) { + $data = file_get_contents( $file ); + $length = strlen( $data ); + + $offset = 13; // 6-byte header plus 7-byte logical screen descriptor. + $flags = ord( $data[10] ); + if ( $flags & 0x80 ) { + $offset += 3 * ( 2 << ( $flags & 0x07 ) ); // Global colour table. + } + + $frames = 0; + while ( $offset < $length ) { + $block = ord( $data[ $offset ] ); + + if ( 0x3B === $block ) { // Trailer. + break; + } + + if ( 0x2C === $block ) { // Image descriptor. + $packed = ord( $data[ $offset + 9 ] ); + $offset += 10; + if ( $packed & 0x80 ) { + $offset += 3 * ( 2 << ( $packed & 0x07 ) ); // Local colour table. + } + ++$offset; // LZW minimum code size. + $offset = $this->skip_gif_sub_blocks( $data, $offset ); + ++$frames; + continue; + } + + if ( 0x21 === $block ) { // Extension. + $offset += 2; // Introducer plus label. + $offset = $this->skip_gif_sub_blocks( $data, $offset ); + continue; + } + + break; // Unknown block; stop rather than misread. + } + + return $frames; + } + + /** + * Advances past a run of GIF data sub-blocks. + * + * @param string $data The GIF file contents. + * @param int $offset The offset of the first sub-block. + * @return int The offset just past the terminating zero-length sub-block. + */ + private function skip_gif_sub_blocks( $data, $offset ) { + $length = strlen( $data ); + + while ( $offset < $length ) { + $size = ord( $data[ $offset ] ); + ++$offset; + if ( 0 === $size ) { + break; + } + $offset += $size; + } + + return $offset; + } + /** * Tests that alpha transparency survives a resize. * From e498404826ae8dadbea99207f29a191716e9209c Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Wed, 7 Oct 2026 14:06:45 -0600 Subject: [PATCH 82/84] Vips: Test the truncation case fail_on is responsible for --- .../class-wp-image-editor-vips.php | 8 +-- tests/phpunit/tests/image/editorVips.php | 53 +++++++++++++++---- 2 files changed, 49 insertions(+), 12 deletions(-) diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index 5ccad8f3c572e..6f0ad295e7b5d 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -328,9 +328,11 @@ public function load() { try { /* - * Reject truncated images, as the Imagick and GD editors do. JPEG is the - * exception: damage there is recoverable, and the other editors fill it, so - * a truncated JPEG still loads. + * Reject truncated images, as the Imagick and GD editors do. PNG and WebP + * already fail in the decoder itself; for the other formats this option is + * what turns a partially decoded file into a failure. JPEG is the exception: + * damage there is recoverable, and the other editors fill it, so a truncated + * JPEG still loads. */ $load_mime = wp_is_stream( $this->file ) ? '' : wp_get_image_mime( $this->file ); $load_options = array( 'fail_on' => ( 'image/jpeg' === $load_mime ) ? 'none' : 'truncated' ); diff --git a/tests/phpunit/tests/image/editorVips.php b/tests/phpunit/tests/image/editorVips.php index dc08f613fbe67..265590c92b16c 100644 --- a/tests/phpunit/tests/image/editorVips.php +++ b/tests/phpunit/tests/image/editorVips.php @@ -881,20 +881,21 @@ public static function data_flip_axes() { } /** - * Tests that a truncated image is not saved. + * Tests that a truncated PNG is not saved. * - * The editor asks the loader to fail on truncation, but libvips reads pixels lazily, - * so an encoder that detects the damage from the header rejects the file at load and - * one that does not only reports it when the pixels are first read. Whichever happens, - * a truncated file must not produce output. + * PNG is rejected by the decoder itself, whether or not `fail_on` is passed, so this + * covers the outcome rather than the option. libvips reads pixels lazily, so the + * failure can surface at load or at the first pixel read; either way nothing is + * written. GIF and JPEG are the formats where `fail_on` is what does the work, and + * they are covered separately. */ - public function test_truncated_images_are_not_saved() { + public function test_truncated_png_is_not_saved() { $data = file_get_contents( DIR_TESTDATA . '/images/transparent.png' ); - $file = tempnam( get_temp_dir(), 'vips_truncated_' ) . '.png'; + $file = tempnam( get_temp_dir(), 'vips_truncated_png_' ) . '.png'; file_put_contents( $file, substr( $data, 0, (int) ( strlen( $data ) * 0.6 ) ) ); - $saved_file = tempnam( get_temp_dir(), 'vips_truncated_out_' ) . '.png'; + $saved_file = tempnam( get_temp_dir(), 'vips_truncated_png_out_' ) . '.png'; $vips_image_editor = new WP_Image_Editor_Vips( $file ); $saved = false; @@ -911,7 +912,41 @@ public function test_truncated_images_are_not_saved() { unlink( $saved_file ); } - $this->assertFalse( $saved, 'A truncated image should not be saved.' ); + $this->assertFalse( $saved, 'A truncated PNG should not be saved.' ); + } + + /** + * Tests that a truncated GIF is not saved. + * + * This is the case that `fail_on` is responsible for. Without it libvips reads a + * truncated GIF, warns, and hands back an image, so a damaged upload would be resized + * and saved; with it the load fails. The test therefore fails if the load options are + * removed from WP_Image_Editor_Vips::load(). + */ + public function test_truncated_gif_is_not_saved() { + $data = file_get_contents( DIR_TESTDATA . '/images/test-image.gif' ); + + $file = tempnam( get_temp_dir(), 'vips_truncated_gif_' ) . '.gif'; + file_put_contents( $file, substr( $data, 0, (int) ( strlen( $data ) * 0.6 ) ) ); + + $saved_file = tempnam( get_temp_dir(), 'vips_truncated_gif_out_' ) . '.gif'; + + $vips_image_editor = new WP_Image_Editor_Vips( $file ); + $saved = false; + + if ( ! is_wp_error( $vips_image_editor->load() ) ) { + $vips_image_editor->resize( 5, 5 ); + + $saved = ! is_wp_error( $vips_image_editor->save( $saved_file ) ); + } + + unlink( $file ); + + if ( file_exists( $saved_file ) ) { + unlink( $saved_file ); + } + + $this->assertFalse( $saved, 'A truncated GIF should not be saved.' ); } /** From ce422e7f1f4d7037b2a5c5a07ec27c127cfc268f Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Mon, 12 Oct 2026 15:40:01 -0600 Subject: [PATCH 83/84] Vips: Explain the pixel cap instead of citing a format limit --- src/wp-includes/class-wp-image-editor-vips.php | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index 6f0ad295e7b5d..9e3ca1fffd377 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -382,8 +382,12 @@ public function load() { * pixels. The dimensions are known before that happens, so an oversized image * is refused here rather than after a decoding attempt has exhausted memory. * - * The default is the largest image a JPEG can describe, which is also the - * largest size the other editors handle without special configuration. + * The default is a deliberately conservative guard rather than a format + * limit: a JPEG can describe 65500 pixels per side, and neither the GD nor + * the Imagick editor restricts the size it will attempt. Because the editor + * is chosen before the file is opened, an image above this size fails to + * load rather than falling back to them, so a site that needs larger images + * has to raise this. * * @since 7.2.0 * From 4072bd4a7f4b8c5d073b8949d348cd3e14a4750d Mon Sep 17 00:00:00 2001 From: Nick Chomey <88559987+nickchomey@users.noreply.github.com> Date: Mon, 12 Oct 2026 16:25:28 -0600 Subject: [PATCH 84/84] Vips: Match Imagick on failed stream reads and WebP quality 100 --- .../class-wp-image-editor-vips.php | 42 +++++++++++++++---- 1 file changed, 34 insertions(+), 8 deletions(-) diff --git a/src/wp-includes/class-wp-image-editor-vips.php b/src/wp-includes/class-wp-image-editor-vips.php index 9e3ca1fffd377..59c5f1191dd1e 100644 --- a/src/wp-includes/class-wp-image-editor-vips.php +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -326,6 +326,26 @@ public function load() { // VIPS is memory-efficient but still raise the limit. wp_raise_memory_limit( 'image' ); + /* + * Fetch a stream before attempting to decode it, so that failing to read the + * resource is reported as a load failure rather than as a bad image. The Imagick + * editor draws the same line, and a stream read can throw rather than return false + * when the fetch is refused. + */ + $file_contents = null; + + if ( wp_is_stream( $this->file ) ) { + try { + $file_contents = file_get_contents( $this->file ); + } catch ( Exception $e ) { + $file_contents = false; + } + + if ( false === $file_contents ) { + return new WP_Error( 'error_loading_image', __( 'File does not exist?' ), $this->file ); + } + } + try { /* * Reject truncated images, as the Imagick and GD editors do. PNG and WebP @@ -337,12 +357,8 @@ public function load() { $load_mime = wp_is_stream( $this->file ) ? '' : wp_get_image_mime( $this->file ); $load_options = array( 'fail_on' => ( 'image/jpeg' === $load_mime ) ? 'none' : 'truncated' ); - // Load the image. - if ( wp_is_stream( $this->file ) ) { - $file_contents = file_get_contents( $this->file ); - if ( false === $file_contents ) { - return new WP_Error( 'error_loading_image', __( 'File does not exist?' ), $this->file ); - } + // Decode the stream contents fetched above, or the file itself. + if ( null !== $file_contents ) { $this->image = Jcupitt\Vips\Image::newFromBuffer( $file_contents, '', $load_options ); } else { $this->image = Jcupitt\Vips\Image::newFromFile( $this->file, $load_options ); @@ -1108,8 +1124,18 @@ protected function get_save_options( $image, $mime_type, $metadata_strategy = ar case 'image/webp': $options['Q'] = $this->get_quality(); - // A lossless WebP has no quality to trade away, so it is re-saved losslessly. - if ( $this->lossless ) { + /* + * A lossless WebP has no quality to trade away, so it is re-saved losslessly. + * + * Quality 100 is also written losslessly, because that is what the Imagick + * editor does: ImageMagick's WebP coder reserves quality 100 for lossless, so + * its 99 matches libvips' 100 and its 100 is a jump to lossless. Measured on + * one 768x432 image: Imagick 88,964 bytes at quality 99 against 311,954 at + * 100, and libvips 90,262 at Q100 against 309,444 written losslessly. Writing + * quality 100 lossily would make the same request produce a far smaller file + * than the editor this one sits in front of. + */ + if ( $this->lossless || 100 === $this->get_quality() ) { $options['lossless'] = true; } break;