在 PHP [for Twilio Fax] 中将彩色 PDF 转换为黑白(单色)PDF

Convert color PDF to black and white (monochrome) PDF in PHP [for Twilio Fax]

我正在尝试将彩色 pdf 转换为黑白 pdf。我将使用 pdf 将其发送到 fax 并且我正在使用 Twilio 并且它明确地将彩色 pdf 转换为单色 pdf 然而,我想在我的服务器端进行能够预览结果。

因为我有Imagick,发现一些主题主要在Imagick上,想试试看,但是在Imagick里找不到需要的class。我找到了一些用于灰度的,但传真是明确的黑白(单色),因此与传真案例不同。

我能找到的最接近的是:

->transformImageColorSpace(\Imagick::COLORSPACE_SRGB)

->setImageColorSpace(Imagick::COLORSPACE_GRAY)

但是这些是灰度的,不是单色的。


此外,在 Imagick formums 上,我找到了这些命令,但我不想用 shell_exec 执行(正如我所读到的,有几个缺点)

// I am pretty sure this one should work, but couldn't find how to do it in php:
convert -density 288 in.pdf -resize 25% out.png  

// thus this one:
convert -density 600 in.pdf -threshold 15% -type bilevel -compress fax out.pdf

// Also found this one:
convert -density 288 image.pdf -resize 25% -threshold 50% -type bilevel image.tiff

如何使用上述命令或任何其他 php 兼容方式实现我在 php 中尝试实现的目标? Twilio 是如何做到的?


更新:

预期输出(Twilio 是如何做到的):

使用以下答案:

$img = new Imagick('path/to/document.pdf');
$img->quantizeImage(2,                        // Number of colors
                Imagick::COLORSPACE_GRAY, // Colorspace
                50,                        // Depth tree
                TRUE,                     // Dither
                FALSE);                   // Error correction
$img->writeImage('path/to/output.png')


更新 2:

使用$img->quantizeImage(2, Imagick::COLORSPACE_GRAY, 1, TRUE, FALSE);

使用 Imagick::quantizeImage 将 PDF 设为单色

$img = new Imagick('path/to/document.pdf');
$img->quantizeImage(2,                        // Number of colors
                    Imagick::COLORSPACE_GRAY, // Colorspace
                    1,                        // Depth tree
                    TRUE,                     // Dither
                    FALSE);                   // Error correction
$img->writeImage('path/to/output.png')

例如...

$img = new Imagick();
$img->newPseudoImage(300, 300, 'radial-gradient:');
$img->quantizeImage(2, Imagick::COLORSPACE_GRAY, 1, TRUE, FALSE);
$img->writeImage('output.png');

**

或增加颜色数以允许黑白之间的灰度值。请参阅使用文档 Color Quantization and Dithering 以获取很好的示例。

$img = new Imagick();
$img->newPseudoImage(300, 300, 'radial-gradient:');
$img->quantizeImage(255, Imagick::COLORSPACE_GRAY, 1, TRUE, FALSE);
$img->writeImage('output.png');