From 980092f2229ce4da9e1ef44621f39ea0cfaf6bdb Mon Sep 17 00:00:00 2001 From: Nicolas Lemoine Date: Mon, 7 Sep 2026 20:49:54 +0200 Subject: [PATCH 1/4] fix(core): give a cloned image its own pipeline and meta data Image::__clone() clones the core, but the vips Core declared no __clone() of its own. The shallow copy left both cores holding the same meta collection and the same vips image. The image itself is immutable, but the decoders open the source for a single sequential pass, so only one of the two images could be encoded, the other failed with an out of order read. The clone now gets its own meta collection, as the GD and Imagick cores do, and while the stash is in place it reopens the source instead of sharing the pipeline: a fresh lazy load at no raster cost, with the same option string and band normalisation the decoder applied. Without a stash the vips image stays shared. --- src/Core.php | 41 +++++++++++++++++++ tests/Unit/CoreTest.php | 91 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 132 insertions(+) diff --git a/src/Core.php b/src/Core.php index c5410ea..218e476 100644 --- a/src/Core.php +++ b/src/Core.php @@ -8,6 +8,7 @@ use Intervention\Image\Collection; use Intervention\Image\Drivers\Vips\Source\BufferSource; use Intervention\Image\Drivers\Vips\Source\PathSource; +use Intervention\Image\Drivers\Vips\Traits\CanNormalizeBands; use Intervention\Image\Exceptions\DriverException; use Intervention\Image\Exceptions\ImageException; use Intervention\Image\Exceptions\InvalidArgumentException; @@ -16,6 +17,7 @@ use Intervention\Image\Interfaces\CoreInterface; use Intervention\Image\Interfaces\FrameInterface; use Iterator; +use Jcupitt\Vips\Access; use Jcupitt\Vips\Exception as VipsException; use Jcupitt\Vips\Image as VipsImage; use Traversable; @@ -25,6 +27,8 @@ */ class Core implements CoreInterface, Iterator { + use CanNormalizeBands; + /** * Number of operations that may be chained onto the image before its * pipeline is rendered into memory. @@ -618,4 +622,41 @@ public function __debugInfo(): array return $debug; } + + /** + * Clone instance + * + * The vips image is immutable, so sharing it with the clone is fine on + * its own. What is not is the pipeline behind a decoded image: the + * decoders open the source for a single sequential pass, and only one of + * the two images could walk it. While the stash is in place the clone + * reopens the source instead, a fresh pipeline at no raster cost. Once + * the stash is gone the vips image is shared, and if it is still + * sequential the first of the two images to be evaluated consumes it. + * Core::ensureInMemory() before cloning renders it once for both. + * + * @throws DriverException + */ + public function __clone(): void + { + $this->meta = clone $this->meta; + + if ($this->stashedSource === null) { + return; + } + + try { + $this->vipsImage = $this->normalizeBands( + $this->stashedSource instanceof PathSource + ? VipsImage::newFromFile($this->stashedSource->pathWithOptions(), ['access' => Access::SEQUENTIAL]) + : VipsImage::newFromBuffer( + $this->stashedSource->buffer, + $this->stashedSource->optionString, + ['access' => Access::SEQUENTIAL], + ), + ); + } catch (VipsException $e) { + throw new DriverException('Failed to reopen the image source for the clone', previous: $e); + } + } } diff --git a/tests/Unit/CoreTest.php b/tests/Unit/CoreTest.php index e17dbd0..3a7f7f3 100644 --- a/tests/Unit/CoreTest.php +++ b/tests/Unit/CoreTest.php @@ -219,6 +219,97 @@ public function testCloneKeepsMetaStripped(): void $this->assertTrue((clone $core)->metaStripped()); } + public function testCloneGetsItsOwnMetaCollection(): void + { + $core = new Core($this->vipsImage(10, 10, [255, 0, 0])); + $clone = clone $core; + + $clone->meta()->set('foo', 'bar'); + + $this->assertFalse($core->meta()->has('foo')); + } + + /** + * The decoders open the source for a single sequential pass. A clone that + * shared that pipeline would leave only one of the two images encodable, + * the other fails with an out of order read. + */ + public function testCloneOfDecodedImageEncodesAlongsideTheOriginal(): void + { + $image = ImageManager::usingDriver(Driver::class)->decodeBinary($this->getTestResourceData('test.jpg')); + $clone = clone $image; + + $encodedClone = $clone->encodeUsingFileExtension('jpg'); + $encodedImage = $image->encodeUsingFileExtension('jpg'); + + $this->assertSame((string) $encodedClone, (string) $encodedImage); + } + + public function testCloneOfImageDecodedFromPathEncodesAlongsideTheOriginal(): void + { + $image = $this->readTestImage('test.jpg'); + $clone = clone $image; + + $encodedClone = $clone->encodeUsingFileExtension('jpg'); + $encodedImage = $image->encodeUsingFileExtension('jpg'); + + $this->assertSame((string) $encodedClone, (string) $encodedImage); + } + + /** + * The decoder adds an alpha band to a 3-band sRGB source, the clone has + * to carry it too. + */ + public function testCloneOfDecodedImageKeepsTheAlphaBand(): void + { + $image = $this->readTestImage('test.jpg'); + $clone = clone $image; + + $this->assertSame(4, $image->core()->native()->bands); + $this->assertSame(4, $clone->core()->native()->bands); + } + + public function testCloneOfDecodedAnimationKeepsItsFrames(): void + { + $image = $this->readTestImage('animation.gif'); + $clone = clone $image; + + $this->assertSame(8, $image->count()); + $this->assertSame(8, $clone->count()); + // n-pages counts the pages of the file whether they were loaded or + // not, the height is what tells the frames apart + $this->assertSame($image->core()->native()->height, $clone->core()->native()->height); + } + + /** + * The clone keeps the stash so the resize modifiers still get their + * shrink on load path. + */ + public function testCloneKeepsTheStashedSource(): void + { + $core = new Core($this->vipsImage(10, 10, [255, 0, 0])); + $stash = new PathSource($this->getTestResourcePath('test.jpg')); + $core->setStashedSource($stash); + + $this->assertSame($stash, (clone $core)->stashedSource()); + } + + /** + * Without a stash the clone shares the vips image, which is fine once it + * has been rendered into memory. + */ + public function testCloneOfImageRenderedInMemoryEncodesAlongsideTheOriginal(): void + { + $image = $this->readTestImage('test.jpg')->flip(); + $this->assertNull($image->core()->stashedSource()); + $clone = clone $image; + + $encodedClone = $clone->encodeUsingFileExtension('jpg'); + $encodedImage = $image->encodeUsingFileExtension('jpg'); + + $this->assertSame((string) $encodedClone, (string) $encodedImage); + } + public function testSetNativeLeavesThePipelineLazyBelowTheOperationLimit(): void { $core = new Core($this->vipsImage(10, 10, [255, 0, 0])); From 516aa49c340835b85eeea8b8731e80542529c06a Mon Sep 17 00:00:00 2001 From: Nicolas Lemoine Date: Mon, 7 Sep 2026 20:50:53 +0200 Subject: [PATCH 2/4] fix(core): set the loop count without mutating the shared image setLoops() wrote the field on the vips image in place. The image is shared with any clone, so the change leaked to the other image, and it left the stash in place, so a clone reopening the source came back with the loop count of the file. Work on a copy and hand it to setNative(), which also clears the stash. --- src/Core.php | 10 +++++++++- tests/Unit/CoreTest.php | 19 +++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/src/Core.php b/src/Core.php index 218e476..c0c2db7 100644 --- a/src/Core.php +++ b/src/Core.php @@ -406,11 +406,19 @@ public function loops(): int public function setLoops(int $loops): CoreInterface { try { - $this->vipsImage->set('loop', $loops); + // work on a copy, the vips image is shared with any clone of the + // image and setting the field in place would change both + $native = $this->vipsImage->copy(); + $native->set('loop', $loops); } catch (VipsException $e) { throw new DriverException('Failed to set loop count', previous: $e); } + // this also clears the stashed source, a clone reopens it and would + // otherwise come back with the loop count of the file + // @phpstan-ignore missingType.checkedException + $this->setNative($native); + return $this; } diff --git a/tests/Unit/CoreTest.php b/tests/Unit/CoreTest.php index 3a7f7f3..b0982f1 100644 --- a/tests/Unit/CoreTest.php +++ b/tests/Unit/CoreTest.php @@ -310,6 +310,25 @@ public function testCloneOfImageRenderedInMemoryEncodesAlongsideTheOriginal(): v $this->assertSame((string) $encodedClone, (string) $encodedImage); } + public function testSetLoopsOnCloneLeavesTheOriginalUntouched(): void + { + $this->assertSame(0, $this->core->loops()); + $clone = clone $this->core; + + $clone->setLoops(7); + + $this->assertSame(7, $clone->loops()); + $this->assertSame(0, $this->core->loops()); + } + + public function testCloneOfDecodedAnimationKeepsTheLoopCountSetOnTheOriginal(): void + { + $image = $this->readTestImage('animation.gif'); + $image->setLoops(5); + + $this->assertSame(5, (clone $image)->loops()); + } + public function testSetNativeLeavesThePipelineLazyBelowTheOperationLimit(): void { $core = new Core($this->vipsImage(10, 10, [255, 0, 0])); From 78312c321af01f906c1c18580eb619a314f3f08e Mon Sep 17 00:00:00 2001 From: Nicolas Lemoine Date: Mon, 7 Sep 2026 21:20:41 +0200 Subject: [PATCH 3/4] fix(core): empty the core through setNative() empty() replaced the vips image directly, so the stashed source stayed in place and described an image that was gone. A later resize reloaded the source, and a clone reopening the stash brought it back whole. Route the replacement through setNative(), which clears the stash. --- src/Core.php | 13 ++++++++++++- tests/Unit/CoreTest.php | 24 ++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/src/Core.php b/src/Core.php index c0c2db7..f3f1e88 100644 --- a/src/Core.php +++ b/src/Core.php @@ -498,10 +498,21 @@ public function getAtPosition(int $key = 0, mixed $default = null): mixed * {@inheritdoc} * * @see CollectionInterface::empty() + * + * @throws DriverException */ public function empty(): CollectionInterface { - $this->vipsImage = VipsImage::black(1, 1)->cast($this->vipsImage->format); + try { + $empty = VipsImage::black(1, 1)->cast($this->vipsImage->format); + } catch (VipsException $e) { + throw new DriverException('Failed to empty image core', previous: $e); + } + + // this also clears the stashed source, a clone reopens it and would + // otherwise bring the emptied source back + // @phpstan-ignore missingType.checkedException + $this->setNative($empty); return $this; } diff --git a/tests/Unit/CoreTest.php b/tests/Unit/CoreTest.php index b0982f1..d3199c9 100644 --- a/tests/Unit/CoreTest.php +++ b/tests/Unit/CoreTest.php @@ -182,6 +182,30 @@ public function testSetNativeClearsStashedSource(): void $this->assertNull($core->stashedSource()); } + public function testEmptyClearsTheStashedSource(): void + { + $core = new Core($this->vipsImage(10, 10, [255, 0, 0])); + $core->setStashedSource(new PathSource($this->getTestResourcePath('test.jpg'))); + + $core->empty(); + + $this->assertNull($core->stashedSource()); + } + + /** + * Left in place, the stash would let a clone bring the emptied source back. + */ + public function testCloneOfEmptiedCoreIsEmpty(): void + { + $image = $this->readTestImage('test.jpg'); + $image->core()->empty(); + + $clone = clone $image; + + $this->assertSame(1, $clone->core()->native()->width); + $this->assertSame(1, $clone->core()->native()->height); + } + public function testMetaStrippedIsFalseByDefault(): void { $core = new Core($this->vipsImage(10, 10, [255, 0, 0])); From 15e6c901b8e349b13a7b5e9361aae0050d47dfef Mon Sep 17 00:00:00 2001 From: Nicolas Lemoine Date: Mon, 7 Sep 2026 21:26:35 +0200 Subject: [PATCH 4/4] fix(decoders): stash grayscale sources and replay the decoder's conversion A grayscale source (B_W, GREY16) was not stashed: the decoder converts it to sRGB, and a resize reopening the stash through thumbnail() would have come back grayscale. Without a stash a clone shares the single sequential pipeline, so cloning a decoded grayscale image hit the very failure Core::__clone() fixes for every other source. Move the conversion the decoder applies, grayscale to sRGB and the alpha band on 3-band sRGB, into CanNormalizeSource, and replay it wherever a stashed source is reopened: Core::__clone() and the thumbnail fast path of the resize and cover modifiers. Grayscale sources are stashed like any other, which also gives them the shrink on load path. Core::__clone() gets a helper for the reopen and starts the chained operation count from zero, the pipeline is fresh. Its docblock now says the reopen does I/O and can throw. --- src/Core.php | 57 +++++++----- src/Decoders/NativeObjectDecoder.php | 27 +++--- src/Modifiers/ColorspaceModifier.php | 6 +- src/Modifiers/CoverModifier.php | 6 +- src/Modifiers/ResizeModifier.php | 6 +- src/Traits/CanNormalizeBands.php | 28 ------ src/Traits/CanNormalizeSource.php | 35 ++++++++ tests/Unit/CoreTest.php | 90 +++++++++++++++++++ .../Unit/Decoders/BinaryImageDecoderTest.php | 11 +++ .../Decoders/FilePathImageDecoderTest.php | 11 +++ tests/Unit/Modifiers/CoverModifierTest.php | 18 ++++ tests/Unit/Modifiers/ResizeModifierTest.php | 32 +++++++ 12 files changed, 251 insertions(+), 76 deletions(-) delete mode 100644 src/Traits/CanNormalizeBands.php create mode 100644 src/Traits/CanNormalizeSource.php diff --git a/src/Core.php b/src/Core.php index f3f1e88..3614a38 100644 --- a/src/Core.php +++ b/src/Core.php @@ -8,7 +8,7 @@ use Intervention\Image\Collection; use Intervention\Image\Drivers\Vips\Source\BufferSource; use Intervention\Image\Drivers\Vips\Source\PathSource; -use Intervention\Image\Drivers\Vips\Traits\CanNormalizeBands; +use Intervention\Image\Drivers\Vips\Traits\CanNormalizeSource; use Intervention\Image\Exceptions\DriverException; use Intervention\Image\Exceptions\ImageException; use Intervention\Image\Exceptions\InvalidArgumentException; @@ -27,7 +27,7 @@ */ class Core implements CoreInterface, Iterator { - use CanNormalizeBands; + use CanNormalizeSource; /** * Number of operations that may be chained onto the image before its @@ -614,6 +614,26 @@ public function rewind(): void $this->iteratorIndex = 0; } + /** + * Reopen the stashed source the way the decoder loaded it: the same + * option string, sequential access, and the decoder's normalisation on + * top. + * + * @throws DriverException + */ + private function reopenStashedSource(PathSource|BufferSource $source): VipsImage + { + try { + $vipsImage = $source instanceof PathSource + ? VipsImage::newFromFile($source->pathWithOptions(), ['access' => Access::SEQUENTIAL]) + : VipsImage::newFromBuffer($source->buffer, $source->optionString, ['access' => Access::SEQUENTIAL]); + + return $this->normalizeSource($vipsImage); + } catch (VipsException $e) { + throw new DriverException('Failed to reopen the image source for the clone', previous: $e); + } + } + /** * Show debug info for the current image * @@ -645,14 +665,18 @@ public function __debugInfo(): array /** * Clone instance * - * The vips image is immutable, so sharing it with the clone is fine on + * Operations on a vips image return new images and the core itself never + * writes to the one it holds, so sharing it with the clone is fine on * its own. What is not is the pipeline behind a decoded image: the * decoders open the source for a single sequential pass, and only one of * the two images could walk it. While the stash is in place the clone - * reopens the source instead, a fresh pipeline at no raster cost. Once - * the stash is gone the vips image is shared, and if it is still - * sequential the first of the two images to be evaluated consumes it. - * Core::ensureInMemory() before cloning renders it once for both. + * reopens the source instead, a fresh pipeline at no raster cost. That + * is a header read, or for a buffer a copy of the encoded bytes into + * memory libvips owns, and it can fail: a file that went away since the + * decode throws here rather than at the encode. Once the stash is gone + * the vips image is shared, and if it is still sequential the first of + * the two images to be evaluated consumes it. Core::ensureInMemory() + * before cloning renders it once for both. * * @throws DriverException */ @@ -660,22 +684,9 @@ public function __clone(): void { $this->meta = clone $this->meta; - if ($this->stashedSource === null) { - return; - } - - try { - $this->vipsImage = $this->normalizeBands( - $this->stashedSource instanceof PathSource - ? VipsImage::newFromFile($this->stashedSource->pathWithOptions(), ['access' => Access::SEQUENTIAL]) - : VipsImage::newFromBuffer( - $this->stashedSource->buffer, - $this->stashedSource->optionString, - ['access' => Access::SEQUENTIAL], - ), - ); - } catch (VipsException $e) { - throw new DriverException('Failed to reopen the image source for the clone', previous: $e); + if ($this->stashedSource !== null) { + $this->vipsImage = $this->reopenStashedSource($this->stashedSource); + $this->chainedOperations = 0; } } } diff --git a/src/Decoders/NativeObjectDecoder.php b/src/Decoders/NativeObjectDecoder.php index 41ac0ca..57b1ff4 100644 --- a/src/Decoders/NativeObjectDecoder.php +++ b/src/Decoders/NativeObjectDecoder.php @@ -7,6 +7,7 @@ use Intervention\Image\Drivers\SpecializableDecoder; use Intervention\Image\Drivers\Vips\Core; use Intervention\Image\Drivers\Vips\Modifiers\OrientModifier; +use Intervention\Image\Drivers\Vips\Traits\CanNormalizeSource; use Intervention\Image\Exceptions\ImageDecoderException; use Intervention\Image\Exceptions\InvalidArgumentException; use Intervention\Image\Exceptions\ModifierException; @@ -17,10 +18,11 @@ use Intervention\Image\MediaType; use Jcupitt\Vips\Exception as VipsException; use Jcupitt\Vips\Image as VipsImage; -use Jcupitt\Vips\Interpretation; class NativeObjectDecoder extends SpecializableDecoder implements SpecializedInterface { + use CanNormalizeSource; + /** * {@inheritdoc} * @@ -50,12 +52,10 @@ public function decode(mixed $input): ImageInterface throw new InvalidArgumentException('Image source must be of type ' . VipsImage::class); } - if (in_array($input->interpretation, [Interpretation::B_W, Interpretation::GREY16])) { - $input = $input->icc_transform(Interpretation::SRGB); // normalize to srgb - } - - if ($input->interpretation === Interpretation::SRGB && $input->bands === 3) { - $input = $input->bandjoin_const(255); // add alpha channel + try { + $input = $this->normalizeSource($input); + } catch (VipsException $e) { + throw new ImageDecoderException('Failed to normalize decoded image', previous: $e); } // build image instance @@ -146,20 +146,15 @@ protected function exifRotation(VipsImage $vips): ?int * Return true if the source is in a state where we can safely stash * it for the resize-family modifiers' thumbnail* fast path. * - * Skip stashing when the parent decoder will mutate the in-memory - * VipsImage in a way that makes the stashed source no longer reflect - * the resulting image (auto-orient, BW/GREY16 to SRGB icc_transform). - * The bandjoin_const(255) for SRGB-3-band sources is OK to stash - * because resize modifiers can re-apply the same alpha if needed. + * Skip stashing when the decoder auto-orients the image, a reopened + * source would come back unrotated. The colour normalisation the decoder + * applies (grayscale to sRGB, alpha band) is no obstacle, whoever reopens + * the stash replays it, see CanNormalizeSource. * * @throws StateException */ protected function isStashableSource(VipsImage $vipsImage): bool { - if (in_array($vipsImage->interpretation, [Interpretation::B_W, Interpretation::GREY16], true)) { - return false; - } - if ( $this->driver()->config()->autoOrientation === true && ($this->exifRotation($vipsImage) ?? 1) > 1 diff --git a/src/Modifiers/ColorspaceModifier.php b/src/Modifiers/ColorspaceModifier.php index bfa24af..20b2be9 100644 --- a/src/Modifiers/ColorspaceModifier.php +++ b/src/Modifiers/ColorspaceModifier.php @@ -5,7 +5,7 @@ namespace Intervention\Image\Drivers\Vips\Modifiers; use Intervention\Image\Drivers\Vips\ColorProcessor; -use Intervention\Image\Drivers\Vips\Traits\CanNormalizeBands; +use Intervention\Image\Drivers\Vips\Traits\CanNormalizeSource; use Intervention\Image\Exceptions\DriverException; use Intervention\Image\Exceptions\ModifierException; use Intervention\Image\Exceptions\NotSupportedException; @@ -16,7 +16,7 @@ class ColorspaceModifier extends GenericColorspaceModifier implements SpecializedInterface { - use CanNormalizeBands; + use CanNormalizeSource; /** * {@inheritdoc} @@ -32,7 +32,7 @@ public function apply(ImageInterface $image): ImageInterface $interpretation = ColorProcessor::colorspaceToInterpretation($this->targetColorspace()); try { - $native = $this->normalizeBands( + $native = $this->normalizeSource( $image->core()->native()->colourspace($interpretation), ); } catch (VipsException $e) { diff --git a/src/Modifiers/CoverModifier.php b/src/Modifiers/CoverModifier.php index cd6fa1e..9031695 100644 --- a/src/Modifiers/CoverModifier.php +++ b/src/Modifiers/CoverModifier.php @@ -9,7 +9,7 @@ use Intervention\Image\Drivers\Vips\Core; use Intervention\Image\Drivers\Vips\Source\BufferSource; use Intervention\Image\Drivers\Vips\Source\PathSource; -use Intervention\Image\Drivers\Vips\Traits\CanNormalizeBands; +use Intervention\Image\Drivers\Vips\Traits\CanNormalizeSource; use Intervention\Image\Exceptions\DriverException; use Intervention\Image\Exceptions\InvalidArgumentException; use Intervention\Image\Exceptions\ModifierException; @@ -26,7 +26,7 @@ class CoverModifier extends GenericCoverModifier implements SpecializedInterface { - use CanNormalizeBands; + use CanNormalizeSource; /** * {@inheritdoc} @@ -57,7 +57,7 @@ public function apply(ImageInterface $image): ImageInterface // Fastest path: stash-based thumbnail* (combines load + resize + crop) if ($stash !== null && $isCenter && !$image->isAnimated()) { try { - $native = $this->normalizeBands( + $native = $this->normalizeSource( $this->coverFromStash($stash, $resize, $colorspace), ); } catch (VipsException $e) { diff --git a/src/Modifiers/ResizeModifier.php b/src/Modifiers/ResizeModifier.php index 84411d5..9c04bb1 100644 --- a/src/Modifiers/ResizeModifier.php +++ b/src/Modifiers/ResizeModifier.php @@ -8,7 +8,7 @@ use Intervention\Image\Drivers\Vips\Core; use Intervention\Image\Drivers\Vips\Source\BufferSource; use Intervention\Image\Drivers\Vips\Source\PathSource; -use Intervention\Image\Drivers\Vips\Traits\CanNormalizeBands; +use Intervention\Image\Drivers\Vips\Traits\CanNormalizeSource; use Intervention\Image\Exceptions\DriverException; use Intervention\Image\Exceptions\InvalidArgumentException; use Intervention\Image\Interfaces\ColorspaceInterface; @@ -22,7 +22,7 @@ class ResizeModifier extends GenericResizeModifier implements SpecializedInterface { - use CanNormalizeBands; + use CanNormalizeSource; /** * {@inheritdoc} @@ -41,7 +41,7 @@ public function apply(ImageInterface $image): ImageInterface if ($stash !== null && !$image->isAnimated()) { $core->setNative( - $this->normalizeBands($this->thumbnailFromStash( + $this->normalizeSource($this->thumbnailFromStash( $stash, $resizeTo, $image->colorspace(), diff --git a/src/Traits/CanNormalizeBands.php b/src/Traits/CanNormalizeBands.php deleted file mode 100644 index 19e5d9b..0000000 --- a/src/Traits/CanNormalizeBands.php +++ /dev/null @@ -1,28 +0,0 @@ - 4-band bandjoin that NativeObjectDecoder - * applies on first decode, so the resized image's bandcount matches - * what the rest of the pipeline expects. - * - * @throws VipsException - */ - private function normalizeBands(VipsImage $image): VipsImage - { - if ($image->interpretation === Interpretation::SRGB && $image->bands === 3) { - return $image->bandjoin_const(255); - } - - return $image; - } -} diff --git a/src/Traits/CanNormalizeSource.php b/src/Traits/CanNormalizeSource.php new file mode 100644 index 0000000..288eac8 --- /dev/null +++ b/src/Traits/CanNormalizeSource.php @@ -0,0 +1,35 @@ +interpretation, [Interpretation::B_W, Interpretation::GREY16], true)) { + $image = $image->icc_transform(Interpretation::SRGB); + } + + if ($image->interpretation === Interpretation::SRGB && $image->bands === 3) { + $image = $image->bandjoin_const(255); + } + + return $image; + } +} diff --git a/tests/Unit/CoreTest.php b/tests/Unit/CoreTest.php index d3199c9..f994334 100644 --- a/tests/Unit/CoreTest.php +++ b/tests/Unit/CoreTest.php @@ -5,17 +5,22 @@ namespace Intervention\Image\Drivers\Vips\Tests\Unit; use Intervention\Image\Drivers\Vips\Core; +use Intervention\Image\Drivers\Vips\Decoders\FilePathImageDecoder; use Intervention\Image\Drivers\Vips\Driver; use Intervention\Image\Drivers\Vips\Frame; use Intervention\Image\Drivers\Vips\Source\BufferSource; use Intervention\Image\Drivers\Vips\Source\PathSource; use Intervention\Image\Drivers\Vips\Tests\BaseTestCase; +use Intervention\Image\Exceptions\DriverException; use Intervention\Image\Exceptions\InvalidArgumentException; use Intervention\Image\ImageManager; use Intervention\Image\Interfaces\AnimationFactoryInterface; use Intervention\Image\Interfaces\FrameInterface; +use Jcupitt\Vips\BandFormat; use Jcupitt\Vips\Image as VipsImage; +use Jcupitt\Vips\Interpretation; use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; #[CoversClass(Core::class)] class CoreTest extends BaseTestCase @@ -293,6 +298,58 @@ public function testCloneOfDecodedImageKeepsTheAlphaBand(): void $this->assertSame(4, $clone->core()->native()->bands); } + /** + * The decoder converts a grayscale source to sRGB. The clone has to come + * back the same way, and encodable alongside the original. + */ + #[DataProvider('grayscaleSourcesProvider')] + public function testCloneOfDecodedGrayscaleImageEncodesAlongsideTheOriginal(string $filename): void + { + $image = $this->readTestImage($filename); + $clone = clone $image; + + $this->assertSame(Interpretation::SRGB, $clone->core()->native()->interpretation); + $this->assertSame(4, $clone->core()->native()->bands); + + $encodedClone = $clone->encodeUsingFileExtension('png'); + $encodedImage = $image->encodeUsingFileExtension('png'); + + $this->assertSame((string) $encodedClone, (string) $encodedImage); + } + + /** + * @return array + */ + public static function grayscaleSourcesProvider(): array + { + return [ + 'jpeg' => ['grayscale.jpg'], + 'png' => ['grayscale.png'], + 'png with alpha' => ['grayscale-alpha.png'], + ]; + } + + public function testCloneOfDecodedGrey16ImageEncodesAlongsideTheOriginal(): void + { + $bytes = VipsImage::black(8, 8) + ->add(30000) + ->cast(BandFormat::USHORT) + ->copy(['interpretation' => Interpretation::GREY16]) + ->writeToBuffer('.png'); + $this->assertSame(Interpretation::GREY16, VipsImage::newFromBuffer($bytes)->interpretation); + + $image = ImageManager::usingDriver(Driver::class)->decodeBinary($bytes); + $clone = clone $image; + + $this->assertSame($image->core()->native()->interpretation, $clone->core()->native()->interpretation); + $this->assertSame($image->core()->native()->bands, $clone->core()->native()->bands); + + $encodedClone = $clone->encodeUsingFileExtension('png'); + $encodedImage = $image->encodeUsingFileExtension('png'); + + $this->assertSame((string) $encodedClone, (string) $encodedImage); + } + public function testCloneOfDecodedAnimationKeepsItsFrames(): void { $image = $this->readTestImage('animation.gif'); @@ -305,6 +362,39 @@ public function testCloneOfDecodedAnimationKeepsItsFrames(): void $this->assertSame($image->core()->native()->height, $clone->core()->native()->height); } + public function testCloneOfAnimationDecodedFromBinaryKeepsItsFrames(): void + { + $image = ImageManager::usingDriver(Driver::class)->decodeBinary($this->getTestResourceData('animation.gif')); + $clone = clone $image; + + $this->assertSame(8, $clone->count()); + $this->assertSame($image->core()->native()->height, $clone->core()->native()->height); + } + + public function testModifyingTheCloneLeavesTheOriginalUntouched(): void + { + $image = $this->readTestImage('test.jpg'); + $clone = clone $image; + + $clone->flip(); + + $original = (string) $image->encodeUsingFileExtension('png'); + $this->assertSame((string) $this->readTestImage('test.jpg')->encodeUsingFileExtension('png'), $original); + $this->assertNotSame((string) $clone->encodeUsingFileExtension('png'), $original); + } + + public function testCloneThrowsWhenTheSourceFileIsGone(): void + { + $path = tempnam(sys_get_temp_dir(), 'vips'); + $this->assertNotFalse($path); + copy($this->getTestResourcePath('test.jpg'), $path); + $image = (new Driver())->decodeImage($path, [FilePathImageDecoder::class]); + unlink($path); + + $this->expectException(DriverException::class); + clone $image; + } + /** * The clone keeps the stash so the resize modifiers still get their * shrink on load path. diff --git a/tests/Unit/Decoders/BinaryImageDecoderTest.php b/tests/Unit/Decoders/BinaryImageDecoderTest.php index 04b1018..494a6b9 100644 --- a/tests/Unit/Decoders/BinaryImageDecoderTest.php +++ b/tests/Unit/Decoders/BinaryImageDecoderTest.php @@ -99,4 +99,15 @@ public function testDecodeStashesBufferSourceForCleanSrgbJpeg(): void $this->assertInstanceOf(BufferSource::class, $stash); $this->assertSame($bytes, $stash->buffer); } + + /** + * The decoder converts a grayscale source to sRGB. It is stashed all the + * same, whoever reopens the stash replays the conversion. + */ + public function testDecodeStashesBufferSourceForGrayscale(): void + { + $image = $this->decoder->decode($this->getTestResourceData('grayscale.jpg')); + + $this->assertInstanceOf(BufferSource::class, $image->core()->stashedSource()); + } } diff --git a/tests/Unit/Decoders/FilePathImageDecoderTest.php b/tests/Unit/Decoders/FilePathImageDecoderTest.php index a997459..bfd1ca3 100644 --- a/tests/Unit/Decoders/FilePathImageDecoderTest.php +++ b/tests/Unit/Decoders/FilePathImageDecoderTest.php @@ -74,6 +74,17 @@ public function testDecodeStashesPathSourceForCleanSrgbJpeg(): void $this->assertStringEndsWith('test.jpg', $stash->path); } + /** + * The decoder converts a grayscale source to sRGB. It is stashed all the + * same, whoever reopens the stash replays the conversion. + */ + public function testDecodeStashesPathSourceForGrayscale(): void + { + $image = $this->decoder->decode(self::getTestResourcePath('grayscale.jpg')); + + $this->assertInstanceOf(PathSource::class, $image->core()->stashedSource()); + } + public function testDecodeDoesNotStashWhenAutoOriented(): void { $image = $this->decoder->decode(self::getTestResourcePath('orientation.jpg')); diff --git a/tests/Unit/Modifiers/CoverModifierTest.php b/tests/Unit/Modifiers/CoverModifierTest.php index bc635b8..cfbd961 100644 --- a/tests/Unit/Modifiers/CoverModifierTest.php +++ b/tests/Unit/Modifiers/CoverModifierTest.php @@ -9,6 +9,7 @@ use Intervention\Image\Drivers\Vips\Modifiers\RemoveAnimationModifier; use Intervention\Image\Drivers\Vips\Modifiers\SliceAnimationModifier; use Intervention\Image\Drivers\Vips\Tests\BaseTestCase; +use Jcupitt\Vips\Interpretation; use PHPUnit\Framework\Attributes\CoversClass; use Intervention\Image\Modifiers\CoverModifier; @@ -51,6 +52,23 @@ public function testModifyAnimated(): void ); } + /** + * A grayscale source goes through the stash like any other. The result + * has to be the sRGB image the decoder produced, not the grayscale + * thumbnail libvips makes of the source. + */ + public function testModifyGrayscaleKeepsTheDecodedColorspace(): void + { + $image = $this->readTestImage('grayscale.jpg'); + $this->assertNotNull($image->core()->stashedSource()); + + $image->modify(new CoverModifier(10, 10, 'center')); + + $this->assertSame(Interpretation::SRGB, $image->core()->native()->interpretation); + $this->assertSame(4, $image->core()->native()->bands); + $this->assertColor(114, 114, 114, 255, $image->colorAt(5, 5), 1); + } + public function testModifyCmykSourceProducesValidOutput(): void { $image = $this->readTestImage('cmyk.jpg'); diff --git a/tests/Unit/Modifiers/ResizeModifierTest.php b/tests/Unit/Modifiers/ResizeModifierTest.php index e6e1e93..7297460 100644 --- a/tests/Unit/Modifiers/ResizeModifierTest.php +++ b/tests/Unit/Modifiers/ResizeModifierTest.php @@ -8,6 +8,7 @@ use Intervention\Image\Drivers\Vips\Modifiers\SliceAnimationModifier; use Intervention\Image\Drivers\Vips\Tests\BaseTestCase; use Intervention\Image\Modifiers\ResizeModifier; +use Jcupitt\Vips\Interpretation; use PHPUnit\Framework\Attributes\CoversClass; #[CoversClass(ResizeModifier::class)] @@ -25,6 +26,37 @@ public function testResize(): void $this->assertColor(255, 0, 0, 255, $image->colorAt(150, 70)); } + /** + * A grayscale source goes through the stash like any other. The result + * has to be the sRGB image the decoder produced, not the grayscale + * thumbnail libvips makes of the source. + */ + public function testResizeGrayscaleKeepsTheDecodedColorspace(): void + { + $image = $this->readTestImage('grayscale.jpg'); + $this->assertNotNull($image->core()->stashedSource()); + + $image->modify(new ResizeModifier(10, 10)); + + $this->assertSame(Interpretation::SRGB, $image->core()->native()->interpretation); + $this->assertSame(4, $image->core()->native()->bands); + $this->assertColor(242, 242, 242, 255, $image->colorAt(0, 0), 1); + $this->assertColor(114, 114, 114, 255, $image->colorAt(5, 5), 1); + $this->assertColor(11, 11, 11, 255, $image->colorAt(9, 9), 1); + } + + public function testResizeGrayscaleWithAlphaKeepsTheAlpha(): void + { + $image = $this->readTestImage('grayscale-alpha.png'); + $this->assertNotNull($image->core()->stashedSource()); + + $image->modify(new ResizeModifier(10, 10)); + + $this->assertSame(Interpretation::SRGB, $image->core()->native()->interpretation); + $this->assertSame(4, $image->core()->native()->bands); + $this->assertColor(137, 137, 137, 128, $image->colorAt(5, 5), 1); + } + public function testResizeAnimated(): void { $image = $this->readTestImage('animation.gif');