【问题标题】:pngquant PHP example isn't workingpngquant PHP 示例不起作用
【发布时间】:2016-08-03 10:13:05
【问题描述】:

我正在尝试使用 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 命令输出捕获到变量中?

【问题讨论】:

  • 只是说,PNG 图像已经高度压缩。但仍然是一个经过研究的问题 +1。
  • 我是一名网页设计师。我使用的大多数 PNG 和其他设计师的 PNG 都可以使用此算法压缩 40% 到 70%,并且没有视觉上可观察到的劣化。我认为这是非常值得的:)
  • 你想出解决办法了吗?
  • @sanjihan 不,还没有 sanjihan。
  • 太糟糕了。您使用的是什么操作系统?

标签: php pngquant


【解决方案1】:

正确的文本:“pngquant --force --ext .png --quality=$min_quality-$max_quality ".escapeshellarg( $path_to_png_file)

【讨论】:

  • 即不将压缩后的内容输出到变量中。它只是在磁盘上创建一个新文件。
【解决方案2】:

使用 PHP 包装器 (php-pngquant) 代替 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];
    }
}   

【讨论】:

  • 感谢 dexterb。我将看看这个包装器如何处理原始输出:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-17
  • 1970-01-01
  • 2013-08-02
  • 2017-04-21
  • 2012-07-05
相关资源
最近更新 更多