fix: Apply image format when saving file in ImagickDriver #268
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
After upgrading to the latest version of
spatie/image
we noticed some issues when converting and cropping PDF files withspatie/media-library
. We specify that for each PDF a square JPG thumbnail must be generated, but these turned out to be corrupt.(I initially believed this was a bug in the
spatie/media-library
package but I was wrong. The destination files simply weren't JPGs, but PDFs instead. This was weird, as we definitely specify the output format.)Upon further investigation, it seems like the GD and the Imagick driver handle setting the desired output format slightly differently.
What I discovered was that certain functions like
resizeCanvas
andoverlay
inImagickDriver
actually re-assign theimage
property, thus "losing" the format if it was set prior to calling those transformations (using->format('jpg')
, for example).You can see the reassignment here. Initially, prior to reassigning
$image
the format may have been set, and it can be lost afterwards.A few observations:
$image->getFormat()
goes fromJPG
tospatie/media-library
, since there a temp copy of the original file is created, which is then transformed and saved (as the same format because the extension is now used as a fallback).This problem 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 instance and is reset when the image is saved. (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.)
In order to ensure all tests passed locally, I also had to make sure to check that 'JPEG' is set as the format if the extension or format is specified as 'JFIF', so I added that to the
save
method as well.Let me know if I need to make any further adjustments :)
Cheers!