我正在尝试将彩色 pdf 转换为黑白 pdf。我将使用 pdf 在传真中发送它,并且我正在使用 Twilio,它显式地将彩色 pdf 转换为单色 pdf,但是,我想在我的服务器端执行此操作,以便能够预览结果。
由于我有Imagick,并且发现了一些主要关于Imagick的主题,我想尝试一下,但在Imagick中找不到必要的类(class)。我找到了一些灰度图,但传真明显是黑白(单色)的,因此与传真情况不同。
我能找到的最接近的是:
->transformImageColorSpace(\Imagick::COLORSPACE_SRGB)
和
->setImageColorSpace(Imagick::COLORSPACE_GRAY)
但这些是灰度的,而不是单色的。
此外,在 Imagick 论坛上,我找到了这些命令,但我不想使用 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');
关于php - 在 PHP 中将彩色 PDF 转换为黑白(单色)PDF [适用于 Twilio Fax],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48405760/