diff --git a/src/Drivers/Gd/Modifiers/TrimModifier.php b/src/Drivers/Gd/Modifiers/TrimModifier.php index a93e0ea6..10bc64bb 100644 --- a/src/Drivers/Gd/Modifiers/TrimModifier.php +++ b/src/Drivers/Gd/Modifiers/TrimModifier.php @@ -57,10 +57,16 @@ public function apply(ImageInterface $image): ImageInterface */ private function trimColor(ImageInterface $image): int { + // read raw (unblended) pixel values instead of values composited + // against a background, so sampled corners match the allocated color + imagealphablending($image->core()->native(), false); + imagesavealpha($image->core()->native(), true); + // trim color base $red = 0; $green = 0; $blue = 0; + $alpha = 0; // corner coordinates $size = $image->size(); @@ -92,13 +98,15 @@ private function trimColor(ImageInterface $image): int $red += round(round($rgb['red'] / 51) * 51); $green += round(round($rgb['green'] / 51) * 51); $blue += round(round($rgb['blue'] / 51) * 51); + $alpha += $rgb['alpha']; } $red = (int) round($red / 4); $green = (int) round($green / 4); $blue = (int) round($blue / 4); + $alpha = (int) round($alpha / 4); - $color = imagecolorallocate($image->core()->native(), $red, $green, $blue); + $color = imagecolorallocatealpha($image->core()->native(), $red, $green, $blue, $alpha); if ($color === false) { throw new ModifierException( diff --git a/tests/Unit/Drivers/Gd/Modifiers/TrimModifierTest.php b/tests/Unit/Drivers/Gd/Modifiers/TrimModifierTest.php index b5a663d9..8b01578d 100644 --- a/tests/Unit/Drivers/Gd/Modifiers/TrimModifierTest.php +++ b/tests/Unit/Drivers/Gd/Modifiers/TrimModifierTest.php @@ -52,4 +52,16 @@ public function testTrimAnimated(): void $this->expectException(NotSupportedException::class); $image->modify(new TrimModifier()); } + + public function testTrimTransparentMargin(): void + { + // circle on transparent background, asymmetric margins + // (left 5, top 8, right 12, bottom 15) + $image = $this->readTestImage('trim-transparent.png'); + $this->assertEquals(41, $image->width()); + $this->assertEquals(47, $image->height()); + $image->modify(new TrimModifier()); + $this->assertEquals(25, $image->width()); + $this->assertEquals(25, $image->height()); + } } diff --git a/tests/resources/trim-transparent.png b/tests/resources/trim-transparent.png new file mode 100644 index 00000000..9ad9318b Binary files /dev/null and b/tests/resources/trim-transparent.png differ