Skip to content

Commit 3693d8f

Browse files
authored
Merge pull request #86 from earthiverse/develop
Fix cropping grayscale JPEG images
2 parents 07e6a2c + 3367202 commit 3693d8f

File tree

3 files changed

+21
-3
lines changed

3 files changed

+21
-3
lines changed

src/Modifiers/CropModifier.php

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -76,16 +76,22 @@ private function background(SizeInterface $resizeTo, ImageInterface $image): Vip
7676
$bgColor->channel(Blue::class)->value(),
7777
];
7878

79+
$originalImage = $image->core()->native();
80+
if ($originalImage->bands === 1) {
81+
// Grayscale -> RGB
82+
$originalImage = $originalImage->colourspace('srgb');
83+
}
84+
7985
// original image and background must have the same number of bands
80-
if ($image->core()->native()->hasAlpha()) {
86+
if ($originalImage->hasAlpha()) {
8187
$bands[] = $bgColor->channel(Alpha::class)->value();
8288
}
8389

8490
return VipsImage::black(1, 1)
8591
->add($bgColor->channel(Red::class)->value())
86-
->cast($image->core()->native()->format)
92+
->cast($originalImage->format)
8793
->embed(0, 0, $resizeTo->width(), $resizeTo->height(), ['extend' => Extend::COPY])
88-
->copy(['interpretation' => $image->core()->native()->interpretation])
94+
->copy(['interpretation' => $originalImage->interpretation])
8995
->bandjoin($bands);
9096
}
9197

tests/Unit/Modifiers/CropModifierTest.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,4 +88,16 @@ public function testModifyCropAnimatedSmart(): void
8888
$this->assertEquals(15, $image->height());
8989
$this->assertColor(255, 166, 1, 255, $image->pickColor(8, 8));
9090
}
91+
92+
public function testCropGrayscale(): void
93+
{
94+
$image = $this->readTestImage('grayscale.jpg');
95+
$image->modify(new CropModifier(258, 258, 0, 0, 'ff0000', 'center'));
96+
$this->assertColor(255, 0, 0, 255, $image->pickColor(0, 0));
97+
$this->assertColor(255, 255, 255, 255, $image->pickColor(1, 1));
98+
$this->assertColor(0, 0, 0, 255, $image->pickColor(1, 256));
99+
100+
// Ensure the image is encodable
101+
$image->encode();
102+
}
91103
}

tests/resources/grayscale.jpg

1.67 KB
Loading

0 commit comments

Comments
 (0)