Skip to content

Commit

Permalink
Refactor code
Browse files Browse the repository at this point in the history
  • Loading branch information
olivervogel committed Sep 19, 2024
1 parent 9aaf5d3 commit cf40c11
Showing 1 changed file with 13 additions and 41 deletions.
54 changes: 13 additions & 41 deletions src/Drivers/Imagick/Encoders/PngEncoder.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,7 @@
namespace Intervention\Image\Drivers\Imagick\Encoders;

use Imagick;
use ImagickException;
use Intervention\Image\Encoders\PngEncoder as GenericPngEncoder;
use Intervention\Image\Exceptions\AnimationException;
use Intervention\Image\Exceptions\RuntimeException;
use Intervention\Image\Exceptions\ColorException;
use Intervention\Image\Interfaces\EncodedImageInterface;
use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\SpecializedInterface;
Expand All @@ -23,7 +19,15 @@ class PngEncoder extends GenericPngEncoder implements SpecializedInterface
*/
public function encode(ImageInterface $image): EncodedImageInterface
{
$output = $this->prepareOutput($image);
if ($this->indexed) {
// reduce colors
$output = clone $image;
$output->reduceColors(256);

$output = $output->core()->native();
} else {
$output = clone $image->core()->native();
}

$output->setCompression(Imagick::COMPRESSION_ZIP);
$output->setImageCompression(Imagick::COMPRESSION_ZIP);
Expand All @@ -33,42 +37,10 @@ public function encode(ImageInterface $image): EncodedImageInterface
}

return $this->createEncodedImage(function ($pointer) use ($output) {
$output->writeImageFile($pointer, $this->format());
$output->writeImageFile(
$pointer,
$this->indexed ? 'PNG' : 'PNG32',
);
});
}

/**
* Prepare given image instance for PNG format output according to encoder settings
*
* @param ImageInterface $image
* @throws AnimationException
* @throws RuntimeException
* @throws ColorException
* @throws ImagickException
* @return Imagick
*/
private function prepareOutput(ImageInterface $image): Imagick
{
$output = clone $image;

if ($this->indexed) {
// reduce colors
$output->reduceColors(256);
$output = $output->core()->native();

return $output;
}

$output = clone $image->core()->native();

return $output;
}

private function format(): string
{
return match ($this->indexed) {
true => 'PNG',
false => 'PNG32', // ensure to encode PNG image type 6 (true color alpha)
};
}
}

0 comments on commit cf40c11

Please sign in to comment.