最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - Imagick "Unable to set image alpha channel" error when turning PDF into JPG - Stack Overflow

programmeradmin0浏览0评论

First of all, this all involves older versions of both PHP and Imagick, that we cannot update at the moment due to technical constraints.

In our project we preview PDF contents to users by splitting the PDF file into a sub-file for each page, then using Imagick to turn each page into a JPG file, which is displayed. Here's the code:

$imagePath = $path . '/' . $filename . '_' . time() . '.jpg';
$im = new Imagick();
//[0] for the first page  
$im->readImage($file . '[0]');
$im->setImageFormat('jpg');
//to avoid a black background
$im->setBackgroundColor('white');
$im->setImageFilename($imagePath);
// reduce image size 
$im->scaleImage(250, 250, true);
//to avoid a black background
$im->mergeImageLayers(Imagick::LAYERMETHOD_FLATTEN);
// issue with imagick version, use the raw value
$im->setImageAlphaChannel(12);
// $im->setImageAlphaChannel(Imagick::ALPHACHANNEL_REMOVE);
if ($im->writeImage()) {
    return $imagePath;
} else {
    $this->loggerService->logging(<error stuff>);
    throw new Exception("Error while generating the picture for a PDF file.");
}

For a specific file this returns

Uncaught PHP Exception ImagickException: "Unable to set image alpha channel"

at

$im->setImageAlphaChannel(12);

Our production and testing environments use PHP 5.5.9 and ImageMagick 6.7.7-10.
I don't have the issue when using ImageMagick 6.9.7-4 on a local environment, so this might be an issue fixed in later versions but again, I don't have the option of upgrading.

The error only occurs on some pages and this PDF file has annotations and some pages that appear to be filled forms (either in word then converted to PDF, or directly in PDF then saved as read-only). I assume some of that may not be considered the same layer or part of the PDF page than the base content, and impact whatever it is the method does (removing image transparency as far as I can tell).

EDIT : as suggested in comments I tried commenting the line since JPGs aren't supposed to handle transparency, but that gave me a black background on most pages (except some of the ones that crash). Switching the format to PNG doesn't remove the error either. Switching and commenting the line seems to do the trick, but I'm not comfortable calling it a day without understanding the cause for the error.

Any idea what, from either the PDF or the code (or the Imagick/Imagemagick version) might be causing this? Thanks in advance!

发布评论

评论列表(0)

  1. 暂无评论