我正在尝试使用pngquant https://pngquant.org/使用 WAMP 动态压缩 PNG 图像的压缩算法。他们提供了一个PHP 示例 https://pngquant.org/php.html(我认为)应该使用Windows 命令行二进制文件 https://pngquant.org/pngquant-windows.zip,我已将其放入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);
似乎也捕获了正确的输出,但以数组的形式,我真的不知道如何将其转换回图像文件。我想捕获变量中的输出,以便我可以使用进一步的压缩算法和操作并将其作为可下载文件发送给用户。
我已经阅读了system() vs exec() vs shell_exec() vs passthrough() vs proc_open() vs popen() 之间的区别 https://stackoverflow.com/a/21016100/2051323。 Shell_exec() 似乎是正确的选择,但是它在 php.net 上说shell_exec() 的 http://php.net/manual/en/function.shell-exec.php输出一个字符串。这会是一个问题吗?如何正确捕捉pngquant - < test.png
命令输出到变量?
使用 PHP 包装器 (php-pngquant https://github.com/ourcodeworld/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];
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)