php - 在 PHP 中将彩色 PDF 转换为黑白(单色)PDF [适用于 Twilio Fax]

标签 php pdf imagemagick twilio imagick

我正在尝试将彩色 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 如何实现):

enter image description here

使用以下答案:

$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')

enter image description here


更新2:

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

enter image description here

最佳答案

使用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');

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');

output.png

关于php - 在 PHP 中将彩色 PDF 转换为黑白(单色)PDF [适用于 Twilio Fax],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48405760/

相关文章:

php - 没有为菜单实现正确​​的链接 rel CSS 样式表

php - 从浏览器访问网络服务器。不是来自xcode

php - php、perl 和 python 中的 HTTP header

ios - 在 UIWebView 上查看下载的 PDF

php - ImageMagick - 将多页 PDF 转换为一张图像

php - 输出 1/0//Yes/No 的比较工具

cocoa - 从不同分辨率的 PDFPage 中提取 NSImage

c# - 在 iTextSharp 中设置表格高度

c# - Mac 上 Mono 中的 DllImport 出现 DllNotFoundException : wrong architecture

bash - 为文件夹中的每个图像生成缩略图