Skip to content

Commit

Permalink
fix: GdDriver resizeCanvas save alpha channel; (#266)
Browse files Browse the repository at this point in the history
* fix: GdDriver resizeCanvas save alpha channel;

* test: GD resizeCanvas for pngs with transparent bg;

* test: fix failing GD resizeCanvas for pngs with transparent bg;

* chore: delete loose use in ResizeTest;
  • Loading branch information
olexoliinyk0 authored Jul 18, 2024
1 parent 3fadd72 commit 3e3ae45
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/Drivers/Gd/GdDriver.php
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,7 @@ public function resizeCanvas(
// even if background-color is set
$transparent = imagecolorallocatealpha($canvas->image, 255, 255, 255, 127);
imagealphablending($canvas->image, false); // do not blend / just overwrite
imagesavealpha($canvas->image, true); // save alpha channel
imagefilledrectangle($canvas->image, $destinationX, $destinationY, $destinationX + $sourceWidth - 1, $destinationY + $sourceHeight - 1, $transparent);

// copy image into new canvas
Expand Down
20 changes: 20 additions & 0 deletions tests/Manipulations/ResizeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,23 @@

assertMatchesImageSnapshot($targetFile);
})->with('drivers');

it('can resize canvas of transparent PNGs without loosing transparency when GD is used', function (ImageDriver $driver) {
if ($driver->driverName() !== 'gd') {
return $this->expectNotToPerformAssertions();
}

$targetFile = $this->tempDir->path("{$driver->driverName()}/resize-with-transparent-png.png");
$image = $driver->loadFile(getTestFile('transparent.png')); // 1640x923
$transparentColor = imagecolorallocatealpha($image->image(), 255, 255, 255, 127);

expect($image->getHeight())->toEqual(923);
expect($image->pickColor(0, 0, \Spatie\Image\Enums\ColorFormat::Int))->toEqual($transparentColor);

// make it square, so height is added top and bottom, bg transparent
$image->resizeCanvas(1640, 1640, \Spatie\Image\Enums\AlignPosition::Center, false, $image->pickColor(0, 0, \Spatie\Image\Enums\ColorFormat::Rgba))->save($targetFile);

$targetImage = $driver->loadFile($targetFile);
expect($targetImage->getHeight())->toEqual(1640);
expect($targetImage->pickColor(0, 0, \Spatie\Image\Enums\ColorFormat::Int))->toEqual($transparentColor);
})->with('drivers');

0 comments on commit 3e3ae45

Please sign in to comment.