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
87 changes: 78 additions & 9 deletions src/Modifiers/RotateModifier.php
Original file line number Diff line number Diff line change
Expand Up @@ -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}
*
Expand All @@ -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(),
Expand Down Expand Up @@ -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<float> $color
* @return array<float>
*/
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);
}
}
74 changes: 74 additions & 0 deletions tests/Unit/Modifiers/RotateModifierTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down Expand Up @@ -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]);
}
}