diff --git a/composer.json b/composer.json index f61b6e5e72854..a02f3a9227ea3 100644 --- a/composer.json +++ b/composer.json @@ -21,6 +21,7 @@ "ext-curl": "*", "ext-dom": "*", "ext-exif": "*", + "ext-ffi": "*", "ext-fileinfo": "*", "ext-filter": "*", "ext-ftp": "*", diff --git a/docker-compose.vips.yml b/docker-compose.vips.yml new file mode 100644 index 0000000000000..24cfba2fbc700 --- /dev/null +++ b/docker-compose.vips.yml @@ -0,0 +1,31 @@ +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 + 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 + + 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/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-admin/includes/class-wp-debug-data.php b/src/wp-admin/includes/class-wp-debug-data.php index 76e1cc2c9419f..9dcc13414e9f4 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,36 @@ private static function get_wp_media(): array { ); } + 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', + '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..987a41b894b17 100644 --- a/src/wp-admin/includes/class-wp-site-health.php +++ b/src/wp-admin/includes/class-wp-site-health.php @@ -1032,6 +1032,15 @@ 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, + ), ); /** diff --git a/src/wp-includes/class-wp-image-editor-imagick.php b/src/wp-includes/class-wp-image-editor-imagick.php index 0be31905eae81..b26958cd383a8 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 * @@ -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 new file mode 100644 index 0000000000000..59c5f1191dd1e --- /dev/null +++ b/src/wp-includes/class-wp-image-editor-vips.php @@ -0,0 +1,1286 @@ + + */ + 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. + * + * 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() ) { + static $supported = null; + + if ( null !== $supported ) { + return $supported; + } + + $supported = false; + + // 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; + } + + /* + * 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(); + if ( empty( $version ) || ! self::is_supported_version( $version ) ) { + return false; + } + } catch ( Exception $e ) { + return false; + } + + $supported = true; + + return true; + } + + /** + * Checks whether a libvips version is new enough for this editor. + * + * 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 + * + * @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.13', '>=' ); + } + + /** + * Returns how a libvips version reduces an image's metadata. + * + * 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 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 get_metadata_strategy( $version ) { + return array( + 'keep' => version_compare( $version, '8.15', '>=' ), + 'remove' => version_compare( $version, '8.16', '<' ), + ); + } + + /** + * 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. + * + * @since 7.2.0 + * + * @param string $mime_type + * @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 ]; + } + + $extension = strtolower( self::get_extension( $mime_type ) ); + + if ( ! $extension || ! self::test() ) { + self::$mime_support_cache[ $mime_type ] = false; + + return false; + } + + /* + * 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' ); + + $supported = ! in_array( $extension, $runtime_encoder_formats, true ) + && in_array( '.' . $extension, self::get_save_suffixes(), true ); + + if ( ! $supported ) { + // Encode a 1x1 image to test writing, where findLoad() tests only reading. + try { + $test_image = Jcupitt\Vips\Image::black( 1, 1 ); + + $supported = ! empty( $test_image->writeToBuffer( '.' . $extension ) ); + } catch ( Exception $e ) { + $supported = false; + } + } + + self::$mime_support_cache[ $mime_type ] = $supported; + + return $supported; + } + + /** + * Returns the extensions libvips can save images to. + * + * This describes the loaded build rather than any particular image, so it is queried + * once. + * + * @since 7.2.0 + * + * @return string[] Extensions including the leading dot. + */ + protected static function get_save_suffixes() { + if ( null !== self::$save_suffixes ) { + return self::$save_suffixes; + } + + self::$save_suffixes = array(); + + try { + // 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 ] ) ); + } + + // @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 ) ); + } catch ( Exception $e ) { + self::$save_suffixes = array(); + } + + return self::$save_suffixes; + } + + /** + * Loads image from $this->file into new VIPS Image object. + * + * @since 7.2.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' ); + + /* + * 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 + * 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' ); + + // 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 ); + } + + /* + * 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; + + if ( ! $width || ! $height ) { + 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 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 + * + * @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 + // 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; + } + + // 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 ); + + return $this->set_quality(); + } catch ( Exception $e ) { + return new WP_Error( 'invalid_image', $e->getMessage(), $this->file ); + } + } + + /** + * 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. + * + * @since 7.2.0 + * + * @param int|null $width Image width. + * @param int|null $height Image height. + * @return true + */ + protected function update_size( $width = null, $height = null ) { + 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 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. 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; + } + + $image = $this->_resize( $max_w, $max_h, $crop ); + + if ( is_wp_error( $image ) ) { + return $image; + } + + $this->image = $image; + + 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. + * + * `$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' ), $this->file ); + } + + list( $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h ) = $dims; + + try { + $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 ); + } + + // 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, + 'kernel' => $this->get_resampling_kernel(), + ) + ); + } + + $this->update_size( $dst_w, $dst_h ); + $this->resized = true; + + return $image; + } catch ( Exception $e ) { + return new WP_Error( 'image_resize_error', $e->getMessage() ); + } + } + + /** + * Resize multiple images from a single source. + * + * @since 7.2.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(); + + foreach ( $sizes as $size => $size_data ) { + $meta = $this->make_subsize( $size_data ); + + if ( ! is_wp_error( $meta ) ) { + $metadata[ $size ] = $meta; + } + } + + 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; + $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; + $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; + $this->resized = $orig_resized; + + 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, 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'] ); + } + + return $saved; + } + + /** + * Crops Image. + * + * @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. + * @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 ) { + $dst_w = $src_w; + } + + if ( ! $dst_h ) { + $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 ); + } + } + + if ( $src_abs ) { + $src_w -= $src_x; + $src_h -= $src_y; + } + + try { + // 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 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, + 'kernel' => $this->get_resampling_kernel(), + ) + ); + } + + $this->image = $cropped; + $this->update_size( $dst_w, $dst_h ); + $this->resized = true; + + return true; + } catch ( Exception $e ) { + return new WP_Error( 'image_crop_error', $e->getMessage() ); + } + } + + /** + * Rotates current image counter-clockwise by $angle. + * + * @since 7.2.0 + * + * @param float $angle + * @return true|WP_Error + */ + public function rotate( $angle ) { + $angle = -$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 ) { + $this->image = $this->image->rot180(); + } elseif ( 270 === $angle ) { + $this->image = $this->image->rot270(); + } else { + $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 ) ) { + return $result; + } + + return true; + } catch ( Exception $e ) { + return new WP_Error( 'image_rotate_error', $e->getMessage() ); + } + } + + /** + * 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; + + // 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'] ) ) { + $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. + * + * @since 7.2.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 { + // 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(); + } + + if ( $horz ) { + $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. + * + * @since 7.2.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 7.2.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 { + /** 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; + + /* + * The metadata is only reduced on a resized save, and how it is reduced depends on the + * libvips version. See get_metadata_strategy(). + */ + $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, $metadata_strategy ); + + 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, + /** + * 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'], + '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 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. + */ + public function stream( $mime_type = null ) { + list( $filename, $extension, $mime_type ) = $this->get_output_format( null, $mime_type ); + + try { + $save_options = $this->get_save_options( $this->image, $mime_type ); + + // 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() ); + } + } + + /** + * 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 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, $metadata_strategy = array() ) { + $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, and is passed when + * get_metadata_strategy() says the version supports it. + */ + if ( ! empty( $metadata_strategy['keep'] ) ) { + $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['optimize_coding'] = true; + + /** 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': + $options['Q'] = $this->get_quality(); + /** + * 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': + $options['Q'] = $this->get_quality(); + + /* + * 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; + + 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; + + /** 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 + // file it came from. + if ( $this->paletted ) { + $options['palette'] = true; + } + break; + + case 'image/gif': + // 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; + } + + // Of the formats handled above, only PNG and the HEIF family can be asked to + // store fewer bits per sample. + $bit_depth = self::get_save_bit_depth( $image, $mime_type ); + + if ( null !== $bit_depth ) { + $options['bitdepth'] = $bit_depth; + } + + 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`. + * + * 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 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 */ + $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; + } + } +} diff --git a/src/wp-includes/media.php b/src/wp-includes/media.php index 2ffa92f2edba0..250824a11dd10 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' ); @@ -5998,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'], 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..ca4f5d90d2d60 --- /dev/null +++ b/src/wp-includes/php-vips/autoload.php @@ -0,0 +1,47 @@ + + * @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/src/wp-includes/update.php b/src/wp-includes/update.php index 9f4257ab03da6..1b502385e8378 100644 --- a/src/wp-includes/update.php +++ b/src/wp-includes/update.php @@ -180,6 +180,25 @@ function ( $carry, $prefixed_myisam_table ) use ( $all_unprefixed_tables ) { ); } + if ( extension_loaded( 'ffi' ) ) { + require_once ABSPATH . WPINC . '/class-wp-image-editor.php'; + require_once ABSPATH . WPINC . '/class-wp-image-editor-vips.php'; + + 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' ), + ) + ) + ); + } + } + /** * Filters the query arguments sent as part of the core version check. * @@ -203,7 +222,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/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/tests/phpunit/data/images/gif-animated.gif b/tests/phpunit/data/images/gif-animated.gif new file mode 100644 index 0000000000000..9b17b37fa8fdc Binary files /dev/null and b/tests/phpunit/data/images/gif-animated.gif differ 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 0000000000000..677e4c5d2ccd0 Binary files /dev/null and b/tests/phpunit/data/images/test-image-iptc-25x25.jpg differ 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..0bb472d26f981 100644 --- a/tests/phpunit/tests/image/editor.php +++ b/tests/phpunit/tests/image/editor.php @@ -49,6 +49,49 @@ 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. + * + * 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 ); + 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 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 ); + 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. */ diff --git a/tests/phpunit/tests/image/editorVips.php b/tests/phpunit/tests/image/editorVips.php new file mode 100644 index 0000000000000..265590c92b16c --- /dev/null +++ b/tests/phpunit/tests/image/editorVips.php @@ -0,0 +1,1887 @@ +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 ); + + // First, check to see if returned array is as expected. + $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 ); + + // Now, verify real dimensions are as expected. + $image_path = DIR_TESTDATA . '/images/' . $resized[0]['file']; + $this->assertImageDimensions( + $image_path, + $expected_array[0]['width'], + $expected_array[0]['height'] + ); + } + + /** + * 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. + * + * @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' => 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, + ), + ); + + $resized = $vips_image_editor->multi_resize( $sizes_array ); + + // If no images are generated, the returned array is empty. + $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( + + /* + * #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, // 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, // 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, // 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, // Arbitrary negative value. + ), + ); + + $resized = $vips_image_editor->multi_resize( $sizes_array ); + + $expected_array = array( + + // #0 + array( + 'file' => 'waffles-10x7.jpg', + 'width' => 10, + 'height' => 7, + 'mime-type' => 'image/jpeg', + 'filesize' => wp_filesize( dirname( $file ) . '/waffles-10x7.jpg' ), + ), + + // #1 + array( + 'file' => 'waffles-75x50.jpg', + 'width' => 75, + 'height' => 50, + 'mime-type' => 'image/jpeg', + 'filesize' => wp_filesize( dirname( $file ) . '/waffles-75x50.jpg' ), + ), + + // #2 + array( + 'file' => 'waffles-30x20.jpg', + 'width' => 30, + 'height' => 20, + 'mime-type' => 'image/jpeg', + 'filesize' => wp_filesize( dirname( $file ) . '/waffles-30x20.jpg' ), + ), + + // #3 + array( + 'file' => 'waffles-45x400.jpg', + 'width' => 45, + 'height' => 400, + 'mime-type' => 'image/jpeg', + 'filesize' => wp_filesize( dirname( $file ) . '/waffles-45x400.jpg' ), + ), + + // #4 + array( + 'file' => 'waffles-50x33.jpg', + 'width' => 50, + 'height' => 33, + 'mime-type' => 'image/jpeg', + 'filesize' => wp_filesize( dirname( $file ) . '/waffles-50x33.jpg' ), + ), + + // #5 + array( + 'file' => 'waffles-55x37.jpg', + 'width' => 55, + 'height' => 37, + 'mime-type' => 'image/jpeg', + 'filesize' => wp_filesize( dirname( $file ) . '/waffles-55x37.jpg' ), + ), + + // #6 + array( + 'file' => 'waffles-83x55.jpg', + 'width' => 83, + 'height' => 55, + 'mime-type' => 'image/jpeg', + 'filesize' => wp_filesize( dirname( $file ) . '/waffles-83x55.jpg' ), + ), + + // #7 + array( + 'file' => 'waffles-90x60.jpg', + 'width' => 90, + 'height' => 60, + 'mime-type' => 'image/jpeg', + 'filesize' => wp_filesize( dirname( $file ) . '/waffles-90x60.jpg' ), + ), + + // #8 + array( + 'file' => 'waffles-105x70.jpg', + 'width' => 105, + 'height' => 70, + 'mime-type' => 'image/jpeg', + 'filesize' => wp_filesize( dirname( $file ) . '/waffles-105x70.jpg' ), + ), + + // #9 + 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']; + + // Now, verify real dimensions are as expected. + $this->assertImageDimensions( + $image_path, + $expected_array[ $key ]['width'], + $expected_array[ $key ]['height'] + ); + } + } + + /** + * Tests resizing an image with cropping. + */ + 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 cropping an image. + * + * @ticket 51937 + * + * @dataProvider data_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( $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h, $src_abs ); + + $this->assertSame( + array( + '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 height and width must be greater than 0' => array( + 'src_x' => 0, + 'src_y' => 0, + 'src_w' => 50, + 'src_h' => 50, + ), + '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 height and width must be greater than 0' => array( + 'src_x' => 10, + 'src_y' => '10', + 'src_w' => 150, + 'src_h' => 150, + 'dst_w' => 150, + 'dst_h' => 150, + ), + 'dst height and width can be string but must be greater than 0' => 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 height and width 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 height and width can be string but 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 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( $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(); + + $this->assertTrue( $vips_image_editor->rotate( $angle ) ); + + $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, + ), + ), + ); + } + + /** + * 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. + * + * @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 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( $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(); + + $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(); + + $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 = $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 ); + + 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', + ), + ), + ); + } + + /** + * Tests that a truncated PNG is not saved. + * + * 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_png_is_not_saved() { + $data = file_get_contents( DIR_TESTDATA . '/images/transparent.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_png_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 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.' ); + } + + /** + * 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 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.13', true ), + array( '8.14.1', true ), + array( '8.15.1', true ), + array( '8.16.1', true ), + ); + } + + /** + * Tests how each libvips version reduces an image's metadata. + * + * `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_metadata_strategy + * + * @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_metadata_strategy( $version, $keep, $remove ) { + $method = new ReflectionMethod( 'WP_Image_Editor_Vips', 'get_metadata_strategy' ); + $method->setAccessible( true ); + + $this->assertSame( + array( + 'keep' => $keep, + 'remove' => $remove, + ), + $method->invoke( null, $version ) + ); + } + + /** + * Data provider for test_metadata_strategy. + * + * @return array + */ + public static function data_libvips_metadata_strategy() { + return array( + 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 ), + ); + } + + /** + * 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 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. + */ + public function test_streams() { + 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' ), + ), + ); + + $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'] ); + } + + /** + * 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 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(); + + $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(); + // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- Warning is unavoidable. + $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. + */ + 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(); + + $save_to_file = tempnam( get_temp_dir(), '' ) . '.png'; + + $vips_image_editor->save( $save_to_file ); + + // 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 ); + + unlink( $save_to_file ); + } + + /** + * 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'; + + $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 ); + } + + /** + * 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. + * + * 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 + */ + public function test_image_strip_meta_filter() { + $file = DIR_TESTDATA . '/images/test-image-iptc.jpg'; + + $strip_meta = static function () { + return false; + }; + + // 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 ) ); + + $reduced_file = tempnam( get_temp_dir(), 'vips_meta_' ) . '.jpg'; + $vips_image_editor->save( $reduced_file ); + + $reduced = wp_read_image_metadata( $reduced_file ); + unlink( $reduced_file ); + + $this->assertNotEmpty( + $reduced['caption'], + 'Descriptive metadata should be kept when metadata is reduced.' + ); + + // The filter can keep everything instead. + add_filter( 'image_strip_meta', $strip_meta ); + + $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 ); + + 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.' ); + } + + /** + * 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 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. + * + * 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 + */ + 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 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. + * + * 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 ); + } + + /** + * 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 ) ); + } + + /** + * 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' ); + } + + /** + * 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. + * + * @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'] ); + + // 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->assertTrue( $has_alpha, "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. + ), + ); + } + + /** + * 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'] ); + } + + /** + * 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 ); + } +} 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/php-vips/Dockerfile b/tools/local-env/php-vips/Dockerfile new file mode 100644 index 0000000000000..d98d7880e9005 --- /dev/null +++ b/tools/local-env/php-vips/Dockerfile @@ -0,0 +1,34 @@ +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. +# +# 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 \ + 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 diff --git a/tools/local-env/scripts/utils.js b/tools/local-env/scripts/utils.js index 58c02716241d5..8782202198039 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( join( repo_root, 'docker-compose.vips.yml' ) ) ) { + composeFiles.push( 'docker-compose.vips.yml' ); + } if ( existsSync( 'docker-compose.override.yml' ) ) { composeFiles.push( 'docker-compose.override.yml' ); diff --git a/tools/php-vips/README.md b/tools/php-vips/README.md new file mode 100644 index 0000000000000..19ff95035e703 --- /dev/null +++ b/tools/php-vips/README.md @@ -0,0 +1,64 @@ +# 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 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 +``` + +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 + +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. +- 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 new file mode 100755 index 0000000000000..9d0915d540c0d --- /dev/null +++ b/tools/php-vips/installer.sh @@ -0,0 +1,361 @@ +#!/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 +# 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 + +# ----------------------------------------------------------------------------- +# 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 "With neither option, the latest release is installed." + 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 + +# ----------------------------------------------------------------------------- +# Prerequisites +# ----------------------------------------------------------------------------- + +check_command() { + if ! command -v "$1" &> /dev/null; then + echo "Error: '$1' is required but not found in PATH." + exit 1 + 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 +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 +# ----------------------------------------------------------------------------- + +# 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..." +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 + +# 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. +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_HEADER +> "$TARGET_DIR/autoload.php" << 'AUTOLOAD_BODY' +spl_autoload_register( + static function ( $class_name ) { + // Namespace prefix for php-vips. + $vips_prefix = 'Jcupitt\\Vips\\'; + $vips_prefix_len = 13; // strlen( 'Jcupitt\\Vips\\' ) + + // Namespace prefix for scoped dependencies (Psr\Log\*). + $scoped_prefix = 'WordPress\\VipsDependencies\\'; + $scoped_prefix_len = 27; // strlen( 'WordPress\\VipsDependencies\\' ) + + $base_dir = __DIR__; + + // 1. Jcupitt\Vips\* → src/ + if ( 0 === strncmp( $class_name, $vips_prefix, $vips_prefix_len ) ) { + $relative_class = substr( $class_name, $vips_prefix_len ); + $file = $base_dir . '/src/' . str_replace( '\\', '/', $relative_class ) . '.php'; + if ( file_exists( $file ) ) { + require $file; + } + return; + } + + // 2. WordPress\VipsDependencies\* → third-party/ (strip prefix). + if ( 0 === strncmp( $class_name, $scoped_prefix, $scoped_prefix_len ) ) { + $relative_class = substr( $class_name, $scoped_prefix_len ); + $file = $base_dir . '/third-party/' . str_replace( '\\', '/', $relative_class ) . '.php'; + if ( file_exists( $file ) ) { + require $file; + } + return; + } + } +); +AUTOLOAD_BODY + +echo "==> 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(), +);