Skip to content

Commit

Permalink
fix: Apply image format when saving file in ImagickDriver (#268)
Browse files Browse the repository at this point in the history
Certain functions like `resizeCanvas`, `overlay` actually re-assign
the `image` property, thus "losing" the format if it was set prior to
calling those transformations.

This can be avoided by ensuring `setFormat()` on the Imagick image(s)
is only called prior to saving the image, at which point the format
will always be correct when saving the file.

To do this, the format is stored as a property on the driver object.
(The GD driver already does it the same way, so I just made a few
adjustments to bring this driver in line with the GD driver.)
  • Loading branch information
nicoverbruggen authored Jul 26, 2024
1 parent 1faafcc commit 14f93e4
Showing 1 changed file with 19 additions and 10 deletions.
29 changes: 19 additions & 10 deletions src/Drivers/Imagick/ImagickDriver.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ class ImagickDriver implements ImageDriver

protected Imagick $image;

protected ?string $format = null;

protected array $exif = [];

protected string $originalPath;
Expand Down Expand Up @@ -256,19 +258,27 @@ public function save(?string $path = null): static
if (! $path) {
$path = $this->originalPath;
}

$extension = pathinfo($path, PATHINFO_EXTENSION);

if (is_null($this->format)) {
$format = pathinfo($path, PATHINFO_EXTENSION);
} else {
$format = $this->format;
}
$formats = Imagick::queryFormats('*');

if (in_array('JPEG', $formats)) {
$formats[] = 'JFIF';
}

if (! in_array(strtoupper($extension), $formats)) {
throw UnsupportedImageFormat::make($extension);
if (! in_array(strtoupper($format), $formats)) {
throw UnsupportedImageFormat::make($format);
}

foreach ($this->image as $image) {
if (strtoupper($format) === 'JFIF') {
$image->setFormat('JPEG');
} else {
$image->setFormat($format);
}
}

if ($this->isAnimated()) {
$image = $this->image->deconstructImages();
$image->writeImages($path, true);
Expand All @@ -279,6 +289,7 @@ public function save(?string $path = null): static
if ($this->optimize) {
$this->optimizerChain->optimize($path);
}
$this->format = null;

return $this;
}
Expand Down Expand Up @@ -618,9 +629,7 @@ public function quality(int $quality): static

public function format(string $format): static
{
foreach ($this->image as $image) {
$image->setFormat($format);
}
$this->format = $format;

return $this;
}
Expand Down

0 comments on commit 14f93e4

Please sign in to comment.