Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 73 additions & 2 deletions src/Core.php
Original file line number Diff line number Diff line change
Expand Up @@ -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\CanNormalizeSource;
use Intervention\Image\Exceptions\DriverException;
use Intervention\Image\Exceptions\ImageException;
use Intervention\Image\Exceptions\InvalidArgumentException;
Expand All @@ -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;
Expand All @@ -25,6 +27,8 @@
*/
class Core implements CoreInterface, Iterator
{
use CanNormalizeSource;

/**
* Number of operations that may be chained onto the image before its
* pipeline is rendered into memory.
Expand Down Expand Up @@ -402,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;
}

Expand Down Expand Up @@ -486,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;
}
Expand Down Expand Up @@ -591,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
*
Expand Down Expand Up @@ -618,4 +661,32 @@ public function __debugInfo(): array

return $debug;
}

/**
* Clone instance
*
* 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. 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
*/
public function __clone(): void
{
$this->meta = clone $this->meta;

if ($this->stashedSource !== null) {
$this->vipsImage = $this->reopenStashedSource($this->stashedSource);
$this->chainedOperations = 0;
}
}
}
27 changes: 11 additions & 16 deletions src/Decoders/NativeObjectDecoder.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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}
*
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions src/Modifiers/ColorspaceModifier.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -16,7 +16,7 @@

class ColorspaceModifier extends GenericColorspaceModifier implements SpecializedInterface
{
use CanNormalizeBands;
use CanNormalizeSource;

/**
* {@inheritdoc}
Expand All @@ -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) {
Expand Down
6 changes: 3 additions & 3 deletions src/Modifiers/CoverModifier.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -26,7 +26,7 @@

class CoverModifier extends GenericCoverModifier implements SpecializedInterface
{
use CanNormalizeBands;
use CanNormalizeSource;

/**
* {@inheritdoc}
Expand Down Expand Up @@ -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) {
Expand Down
6 changes: 3 additions & 3 deletions src/Modifiers/ResizeModifier.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -22,7 +22,7 @@

class ResizeModifier extends GenericResizeModifier implements SpecializedInterface
{
use CanNormalizeBands;
use CanNormalizeSource;

/**
* {@inheritdoc}
Expand All @@ -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(),
Expand Down
28 changes: 0 additions & 28 deletions src/Traits/CanNormalizeBands.php

This file was deleted.

35 changes: 35 additions & 0 deletions src/Traits/CanNormalizeSource.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

declare(strict_types=1);

namespace Intervention\Image\Drivers\Vips\Traits;

use Jcupitt\Vips\Exception as VipsException;
use Jcupitt\Vips\Image as VipsImage;
use Jcupitt\Vips\Interpretation;

trait CanNormalizeSource
{
/**
* Bring a vips image into the shape the driver works with: grayscale
* (B_W, GREY16) is converted to sRGB, and 3-band sRGB gets an alpha
* band. NativeObjectDecoder applies this to every loaded source. Whoever
* reopens a stashed source, Core::__clone() and the thumbnail fast path
* of the resize modifiers, replays it so the result matches the decoded
* image, and ColorspaceModifier applies it after a conversion.
*
* @throws VipsException
*/
private function normalizeSource(VipsImage $image): VipsImage
{
if (in_array($image->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;
}
}
Loading