From f475b0674331f2971500669cfe754798fe648b90 Mon Sep 17 00:00:00 2001 From: Nicolas Lemoine Date: Wed, 19 Aug 2026 07:30:34 +0200 Subject: [PATCH] fix(modifiers): rotate 16-bit sources at non-quarter angles RotateModifier exports the background color against the image, then adds an alpha band to that image before handing both to similarity(). The exported vector is sized to the bandcount as it was before the band was added, so a three-band source produces a three-element background for a four-band image and libvips throws `linear: vector must have 1 or 4 elements`. Sources with an SRGB interpretation never reach that state, because NativeObjectDecoder normalizes them to four bands on decode. 16-bit PNG and TIFF sources load as RGB16 and keep three bands, so every non-quarter rotation of one throws. Quarter turns are unaffected, they take the rot90/rot180/rot270 path and paint no background at all. Add the alpha band before the color is exported, so the exported vector matches the bandcount similarity() sees, and so the alpha channel of the background color is kept rather than truncated away. Use addalpha() instead of bandjoin_const(255): it picks the opaque value that goes with the interpretation, where a hardcoded 255 leaves a ushort image at 0.4% opacity. Scale the exported color to the value range of the image for the same reason, 0-255 on a 16-bit image paints near black instead of white. Adds three regression tests: an arbitrary angle, an arbitrary angle with a translucent background, and a quarter turn that must not gain an alpha band. --- src/Modifiers/RotateModifier.php | 87 ++++++++++++++++++--- tests/Unit/Modifiers/RotateModifierTest.php | 74 ++++++++++++++++++ 2 files changed, 152 insertions(+), 9 deletions(-) diff --git a/src/Modifiers/RotateModifier.php b/src/Modifiers/RotateModifier.php index d14c418..d0a62b3 100644 --- a/src/Modifiers/RotateModifier.php +++ b/src/Modifiers/RotateModifier.php @@ -13,9 +13,16 @@ use Intervention\Image\Modifiers\RotateModifier as GenericRotateModifier; use Jcupitt\Vips\Exception as VipsException; use Jcupitt\Vips\Image as VipsImage; +use Jcupitt\Vips\Interpretation; class RotateModifier extends GenericRotateModifier implements SpecializedInterface { + /** + * Angles served by rot90/rot180/rot270. They expose no new area and + * therefore paint no background, unlike the similarity() fallback. + */ + private const ANGLES_WITHOUT_BACKGROUND = [0.0, 90.0, -270.0, 180.0, -180.0, -90.0, 270.0]; + /** * {@inheritdoc} * @@ -27,19 +34,31 @@ class RotateModifier extends GenericRotateModifier implements SpecializedInterfa */ public function apply(ImageInterface $image): ImageInterface { - $backgroundColor = $this->driver() - ->colorProcessor($image) - ->export($this->backgroundColor()); - // rot90/rot180/rot270/similarity require non-sequential reads of the // source. Sequentially-decoded sources fail with `out of order read` // when the encoder later walks the pipeline. Core::ensureInMemory($image->core()); + $angle = $this->rotationAngle(); + + // similarity() needs an alpha channel to paint the areas it exposes. + // Sources that decode to three bands (NativeObjectDecoder only adds + // the channel to SRGB sources, so 16-bit ones keep three bands) get + // theirs here, before the background color is exported, so that the + // exported vector is sized to the bandcount similarity() will see. + if (!in_array($angle, self::ANGLES_WITHOUT_BACKGROUND, true)) { + $this->addAlpha($image); + } + + $backgroundColor = $this->scaleToImage( + $this->driver()->colorProcessor($image)->export($this->backgroundColor()), + $image->core()->native(), + ); + $frames = []; foreach ($image as $frame) { try { - $native = match ($this->rotationAngle()) { + $native = match ($angle) { 0.0 => $frame->native(), 90.0, -270.0 => $frame->native()->rot90(), 180.0, -180.0 => $frame->native()->rot180(), @@ -68,13 +87,63 @@ public function apply(ImageInterface $image): ImageInterface */ private function rotate(VipsImage $vipsImage, array $backgroundColor): VipsImage { - if (!$vipsImage->hasAlpha()) { - $vipsImage = $vipsImage->bandjoin_const(255); - } - return $vipsImage->similarity([ 'angle' => $this->rotationAngle(), // TODO: check rotation direction 'background' => $backgroundColor, ]); } + + /** + * Add an alpha channel to the given image unless it already carries one. + * + * addalpha() picks the opaque value that goes with the interpretation of + * the image, where a hardcoded 255 would leave 16-bit sources all but + * fully transparent. + * + * @throws ModifierException + */ + private function addAlpha(ImageInterface $image): void + { + $vipsImage = $image->core()->native(); + + try { + if ($vipsImage->hasAlpha()) { + return; + } + + $image->core()->setNative($vipsImage->addalpha()); + } catch (VipsException $e) { + throw new ModifierException( + 'Failed to apply ' . self::class . ', unable to add alpha channel', + previous: $e, + ); + } + } + + /** + * Scale the exported color to the value range of the given image. + * + * ColorProcessor::export() returns channel values on a 0-255 scale, but + * libvips reads the background of similarity() on the scale that goes + * with the interpretation of the image: 0-65535 for 16-bit sources and + * 0-1 for scRGB ones. The ranges below are the ones libvips itself uses + * to pick an opaque alpha value in addalpha(). + * + * @param array $color + * @return array + */ + private function scaleToImage(array $color, VipsImage $vipsImage): array + { + $max = match ($vipsImage->interpretation) { + Interpretation::RGB16, Interpretation::GREY16 => 65535, + Interpretation::SCRGB => 1, + default => 255, + }; + + if ($max === 255) { + return $color; + } + + return array_map(fn(float $value): float => $value / 255 * $max, $color); + } } diff --git a/tests/Unit/Modifiers/RotateModifierTest.php b/tests/Unit/Modifiers/RotateModifierTest.php index d8fc9a4..d421de3 100644 --- a/tests/Unit/Modifiers/RotateModifierTest.php +++ b/tests/Unit/Modifiers/RotateModifierTest.php @@ -9,9 +9,13 @@ use Intervention\Image\Drivers\Vips\Driver; use Intervention\Image\Drivers\Vips\Tests\BaseTestCase; use Intervention\Image\Encoders\JpegEncoder; +use Intervention\Image\Encoders\PngEncoder; use Intervention\Image\ImageManager; use Intervention\Image\Modifiers\RotateModifier; +use Jcupitt\Vips\BandFormat; +use Jcupitt\Vips\Exception as VipsException; use Jcupitt\Vips\Image as VipsImage; +use Jcupitt\Vips\Interpretation; use PHPUnit\Framework\Attributes\CoversClass; #[CoversClass(RotateModifier::class)] @@ -102,4 +106,74 @@ public function testRotateArbitraryAngleAfterSequentialDecodeAllowsEncoding(): v $bytes = $image->encode(new JpegEncoder(quality: 75))->toString(); $this->assertNotEmpty($bytes); } + + /** + * Regression: sources that decode to three bands without an alpha channel + * threw `linear: vector must have 1 or 4 elements`. The background color is + * exported against the three-band image, but the rotation then adds an + * alpha band and hands the stale three-element vector to similarity(). + * + * 16-bit PNG/TIFF sources are the practical way to get there: the decoder + * only normalizes to four bands when the interpretation is SRGB, and a + * 16-bit source loads as RGB16. + */ + public function testRotateSixteenBitSource(): void + { + $image = (new Driver())->decodeImage(self::sixteenBitPng(), [BinaryImageDecoder::class]); + $image->modify(new RotateModifier(45, 'fff')); + + $rotated = VipsImage::newFromBuffer($image->encode(new PngEncoder())->toString()); + + $this->assertEquals(BandFormat::USHORT, $rotated->format); + $this->assertTrue($rotated->hasAlpha()); + + // the exposed corner has to be opaque white on the 16-bit scale, not + // the 255 that ColorProcessor::export() hands out + $this->assertEquals([65535, 65535, 65535, 65535], $rotated->getpoint(0, 0)); + } + + /** + * The alpha channel of the background color survives the rotation of a + * three-band source, instead of being dropped when the vector is sized to + * the bandcount of the image before the alpha band is added. + */ + public function testRotateSixteenBitSourceKeepsBackgroundAlpha(): void + { + $image = (new Driver())->decodeImage(self::sixteenBitPng(), [BinaryImageDecoder::class]); + $image->modify(new RotateModifier(45, 'ffffff00')); + + $rotated = VipsImage::newFromBuffer($image->encode(new PngEncoder())->toString()); + + $this->assertEquals(0, $rotated->getpoint(0, 0)[3]); + } + + /** + * Quarter turns take the rot90/rot180/rot270 path, which paints no + * background and must not gain an alpha band. + */ + public function testRotateSixteenBitSourceQuarterTurn(): void + { + $image = (new Driver())->decodeImage(self::sixteenBitPng(), [BinaryImageDecoder::class]); + $image->modify(new RotateModifier(90, 'fff')); + + $rotated = VipsImage::newFromBuffer($image->encode(new PngEncoder())->toString()); + + $this->assertEquals(BandFormat::USHORT, $rotated->format); + $this->assertFalse($rotated->hasAlpha()); + } + + /** + * 16-bit RGB PNG, the source shape reported in the issue: three bands, + * ushort, RGB16 interpretation. + * + * @throws VipsException + */ + private static function sixteenBitPng(): string + { + return VipsImage::black(32, 32, ['bands' => 3]) + ->add(30000) + ->cast(BandFormat::USHORT) + ->copy(['interpretation' => Interpretation::RGB16]) + ->writeToBuffer('.png', ['bitdepth' => 16]); + } }