1

我正在尝试使用以下代码(源代码)将 pngquant 与 PHP 一起使用:

<?php 


function compress_png($path_to_png_file, $max_quality = 90)
{
    if (!file_exists($path_to_png_file)) {
        throw new Exception("File does not exist: $path_to_png_file");
    }

    // guarantee that quality won't be worse than that.
    $min_quality = 60;

    // '-' makes it use stdout, required to save to $compressed_png_content variable
    // '<' makes it read from the given file path
    // escapeshellarg() makes this safe to use with any path

    // maybe with more memory ?
    ini_set("memory_limit", "128M");

    // The command should look like: pngquant --quality=60-90 - < "image-original.png"
    $comm = "pngquant --quality=$min_quality-$max_quality - < ".escapeshellarg(    $path_to_png_file);

    $compressed_png_content = shell_exec($comm);

    var_dump($compressed_png_content);

    if (!$compressed_png_content) {
        throw new Exception("Conversion to compressed PNG failed. Is pngquant 1.8+ installed on the server?");
    }

    return $compressed_png_content;
}

echo compress_png("image-original.png");

该函数应该检索 shell_exec 函数的输出。使用输出我应该能够创建一个新的 png 文件,但是shell_exec浏览器中的输出已损坏:�PNG.

注意:该命令的执行是在没有PHP的控制台中成功执行的(pngquant --quality=60-90 - < "image-original.png"

如果我从控制台执行 php 代码,我会收到以下消息:

错误:将图像写入标准输出失败 (16)

我到处搜索都没有任何解决方案,有人可以帮助我或知道可能导致问题的原因吗?

4

1 回答 1

0

php-pngquant 包装器允许您使用 getRawOutput 方法将 PNGQuant生成的图像中的内容直接检索到变量中:

<?php 

use ourcodeworld\PNGQuant\PNGQuant;

$instance = new PNGQuant();

$result = $instance
    ->setImage("/image/to-compress.png")
    ->setQuality(50,80)
    ->getRawOutput();

// Result is an array with the following structure
// $result = array(
//    'statusCode' => 0,
//    'tempFile' => "/tmp/example-temporal.png",
//    'imageData' => [String] (use the imagecreatefromstring function to get the binary data)
//)

// Get the binary data of the image
$imageData = imagecreatefromstring($result["imageData"]);

// Save the PNG Image from the raw data into a file or do whatever you want.
imagepng($imageData , '/result_image.png');

在底层,包装器在 PNGQuant 中提供一个临时文件作为输出参数,然后 pngquant 会将压缩图像写入该文件,并在结果数组中检索其内容。您仍然可以使用statusCode结果数组的索引来验证 PNGQuant 的退出代码。

于 2017-04-10T21:39:57.253 回答