I have an odd issue that I cannot get to the bottom of. I'm using Imagick to generate JPG thumbnails of PDFs that are uploaded to a custom admin tool. However, Imagick is creating PDF files even though setImageFormat is set to JPEG and to add to the confusion this only happens when a PDF file has a single page. If it's a multipage PDF, the jpg thumbnails are created.
public function generateCopies() {
if (empty($this->copyPathFormats)) {
return True;
}
if (! is_array($this->copyPathFormats)) {
throw new \InvalidArgumentException('Asset::copyPathFormat must be an array. '.gettype($this->copyPathFormats).' provided.');
}
foreach ($this->copyPathFormats as $key => $copyPathFormat) {
if ($key === 'finder') {
continue;
}
$path = $this->basePath.$this->pathParamSubstitution($copyPathFormat, $this->pathParam);
if (! (is_dir($path) || mkdir($path, 0777, True))) {
throw new \RuntimeException($path.' could not be found or created.');
}
$img = new \Imagick($this->path.$this->name);
$img->setImageCompressionQuality( 89 );
$copyName = $this->name;
$format = $img->getImageFormat();
if ($format === 'PDF') {
$img = new \Imagick();
$img->setResolution(150,150);
$img->readImage($this->path.$this->name.'[0]');
$img->setImageCompressionQuality( 70 );
$img = $img->flattenImages();
$img->setImageFormat('jpeg');
$filename = pathinfo($this->name, PATHINFO_FILENAME);
$copyName = $filename.'.jpg';
}
$geometry = $img->getImageGeometry();
$width = $geometry['width'] >= $geometry['height'] ? $this->copySizeConstraints[$key] : 0;
$height = $geometry['height'] > $geometry['width'] ? $this->copySizeConstraints[$key] : 0;
if ($img->scaleImage($width,$height,False) !== True) {
\RuntimeException('Cannot resize the image.');
}
if ($img->writeImage($path.$copyName) !== True) {
throw new \RuntimeException('Cannot write the resized copy to '.$path.$this->name);
}
$img->destroy();
}
return True;
}
Solved the problem here. Even though the PDFs are indeed PDFs, they were exported from Adobe Illustrator. Imagemagick therefore was interpreting these as AI files. Once I updated my if statement to also include AI, things started working as expected.
$img = new \Imagick($this->path.$this->name);
$copyName = $this->name;
$format = $img->getImageFormat();
if ($format === 'PDF' or $format === 'AI') {
$img = new \Imagick();
$img->setResolution(150,150);
$img->setColorspace(1);
$img->readImage($this->path.$this->name.'[0]');
$img->setImageFormat('jpeg');
$img->setFormat('jpeg');
$img->setImageCompressionQuality( 70 );
$img = $img->flattenImages();
$filename = pathinfo($this->name, PATHINFO_FILENAME);
$copyName = $filename.'.jpg';
}