Skip to content

Commit

Permalink
Refactor code
Browse files Browse the repository at this point in the history
  • Loading branch information
olivervogel committed Jul 14, 2024
1 parent 51f23b2 commit 184fd40
Showing 1 changed file with 12 additions and 23 deletions.
35 changes: 12 additions & 23 deletions src/Drivers/Gd/Encoders/PngEncoder.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,41 +4,30 @@

namespace Intervention\Image\Drivers\Gd\Encoders;

use GdImage;
use Intervention\Image\EncodedImage;
use Intervention\Image\Encoders\PngEncoder as GenericPngEncoder;
use Intervention\Image\Exceptions\RuntimeException;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;

class PngEncoder extends GenericPngEncoder implements SpecializedInterface
{
public function encode(ImageInterface $image): EncodedImage
{
$output = $this->maybeToPalette(clone $image); // use clone because colors may be reduced
// use clone because colors may be reduced and original
// image should not be altered by encoder
$output = clone $image;

$data = $this->buffered(function () use ($output) {
imageinterlace($output, $this->interlaced);
imagesavealpha($output, true);
imagepng($output, null, -1);
if ($this->indexed) {
$output->reduceColors(256)->core()->native();
}

$gd = $output->core()->native();
$data = $this->buffered(function () use ($gd) {
imageinterlace($gd, $this->interlaced);
imagesavealpha($gd, true);
imagepng($gd, null, -1);
});

return new EncodedImage($data, 'image/png');
}

/**
* Transform given image to indexed palette version according to encoder settings
*
* @param ImageInterface $image
* @throws RuntimeException
* @return GdImage
*/
private function maybeToPalette(ImageInterface $image): GdImage
{
if ($this->indexed === false) {
return $image->core()->native();
}

return $image->reduceColors(256)->core()->native();
}
}

0 comments on commit 184fd40

Please sign in to comment.