【问题标题】:Convert color PDF to black and white (monochrome) PDF in PHP [for Twilio Fax]在 PHP [for Twilio Fax] 中将彩色 PDF 转换为黑白(单色)PDF
【发布时间】:2018-07-02 12:16:24
【问题描述】:

我正在尝试将彩色 pdf 转换为黑白 pdf。我将使用 pdf 在 fax 中发送它,我正在使用 Twilio,它明确地将彩色 pdf 转换为单色 pdf 但是,我想在我的服务器端执行它以便能够预览结果。

由于我有 Imagick,并且发现了一些主要关于 Imagick 的主题,我想尝试一下,但我在 Imagick 中找不到必要的课程。我找到了一些灰度,但传真明显是黑白(单色),因此与传真情况不同。

我能找到的最接近的是:

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

【问题讨论】:

    标签: php pdf imagemagick twilio imagick


    【解决方案1】:

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

    【讨论】:

    • 感谢您的意见@emcconville。我已经更新了关于您的答案的答案。你能查一下吗?
    • 出于好奇,有没有关于如何使用多页 pdf 执行此操作的建议?
    • @Matthew,如果您有任何问题,please ask。评论部分不提供正确回答的实用程序。
    猜你喜欢
    • 1970-01-01
    • 2011-12-10
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 2018-01-03
    • 1970-01-01
    • 2014-03-12
    • 1970-01-01
    相关资源
    最近更新 更多