首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >shell_exec输出到变量的pngquant

shell_exec输出到变量的pngquant
EN

Stack Overflow用户
提问于 2017-01-09 19:20:48
回答 1查看 712关注 0票数 1

我试图使用以下代码(来源)对PHP使用pngquant:

代码语言:javascript
复制
<?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

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

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

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

我到处找都找不到解决办法,有人能帮我吗,或者知道是什么导致了这个问题?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-04-10 21:39:57

php-pngquant包装器允许从PNGQuant生成的图像中直接检索到变量使用getRawOutput方法中。

代码语言:javascript
复制
<?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将压缩的图像写入该文件,并在结果数组中检索其内容。您仍然可以使用结果数组的PNGQuant索引验证statusCode的退出代码。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41555353

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档