php - pngquant PHP 示例不工作

标签 php pngquant

我正在尝试使用 pngquant使用 WAMP 动态压缩 PNG 图像的压缩算法。他们提供了一个 PHP example那(我认为)应该使用 command line binary for Windows ,我已将其放入 system32文件夹,我可以从命令行的任何位置访问。

我以他们为例并将问题追溯到$compressed_png_content = shell_exec("pngquant --quality=$min_quality-$max_quality - < ".escapeshellarg( $path_to_png_file));线。我已将其简化为 var_dump(shell_exec('pngquant - < test.png'));但它只输出前 5 个字符,即使 passthru('pngquant - < test.png');似乎将正确的输出作为字符串发送给用户。 exec('pngquant - < test.png',$output); var_dump($output);似乎也捕获了正确的输出,但是以数组的形式,我真的不知道如何将其转换回图像文件。我想在变量中捕获输出,以便我可以使用进一步的压缩算法和操作并将其作为可下载文件发送给用户。

我已经阅读了 diferences between system() vs exec() vs shell_exec() vs passthru() vs proc_open() vs popen() . Shell_exec() 似乎是正确的选择,但是它在 php.net 上说 shell_exec()'s输出一个字符串。这会是个问题吗?如何正确捕获 pngquant - < test.png命令输出到变量?

最佳答案

改用 PNGQuant 的 PHP 包装器 ( php-pngquant ),我遇到了同样的问题,这个非官方包装器终于救了我。

function compress_image($source_path, $destination_path, $quality){
     $instance = new PNGQuant();

    // Change the path to the binary of pngquant, for example in windows would be (with an example path):
    $instance->setBinaryPath("E:\\wamp64\\www\\testing\\pngquant\\pngquant.exe")
        // Other options of PNGQuant here
        ->execute();

    // Set the path to the image to compress
    $result = $instance->setImage($source_path)
        // Overwrite output file if exists, otherwise pngquant will generate output ...
        ->overwriteExistingFile()
        // As the quality in pngquant isn't fixed (it uses a range)
        // set the minimum quality to 60
        ->setQuality(60, $quality)
        // Retrieve RAW data from pngquant
        ->getRawOutput();

    $exit_code = $result["statusCode"];


    // if exit code is equal to 0 then everything went right !
    if($exit_code == 0){

        $rawImage = imagecreatefromstring($result["imageData"]);

        // Example Save the PNG Image from the raw data into a file or do whatever you want.
        imagepng($rawImage , $destination_path);

        echo "Image succesfully compressed, do something with the raw Data";
    }else{
        echo "Something went wrong (status code $exit_code)  with description: ". $instance->getErrorTable()[(string) $exit_code];
    }
}   

关于php - pngquant PHP 示例不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36579368/

相关文章:

java - 如何从 PHP 脚本、Java 程序回调进程状态到调用 bash shell

php - 使用 MYSQL Like '"%$* %"' 创建搜索过滤器

php - htaccess Symfony2 将所有 *.php 页面(除了 app.php)重定向到 app.php

Gulp Imagemin 未完成

javascript - 模块构建错误 : pngquant ENOENT - webpack build succeeds on local OS X, 在 AWS Ubuntu 16.04 服务器上失败

php - 如何使用 pngquant 在 ubuntu 服务器上使用 php 压缩 jpeg 文件

javascript - 将 Javascript 与 MPDF 结合使用

php - 如何在我的开发网站的页面顶部显示当前的 git 分支名称?