首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >pngquant和shell_exec检查状态码,然后保存图像

pngquant和shell_exec检查状态码,然后保存图像
EN

Stack Overflow用户
提问于 2020-07-01 08:48:48
回答 1查看 52关注 0票数 0

我有下面的代码,它似乎正在生成一个损坏的图像。Photoshop显示"PNG文件被ASCII转换损坏“

代码语言:javascript
复制
    $path_pngquant = "pngquant";
    $status_code = null;
    $image = null;
    $output = null;

    $image_input_escaped = escapeshellarg('test.png');

    $command = "$path_pngquant --strip -- - < $image_input_escaped";

    // Execute the command
    exec($command, $output, $status_code);

    if($status_code == 0)
    {
        //0 means success
        $image = implode('', $output);
        file_put_contents('test_2.png', $image);
    }
EN

回答 1

Stack Overflow用户

发布于 2020-07-01 11:33:35

exec会弄乱二进制流,您需要的是以二进制模式打开从其读取的输出流。幸运的是,popen正是为此而设计的

代码语言:javascript
复制
    <?php
 $path_pngquant = "pngquant";
    $status_code = null;
    $image = null;
    $output = null;

    $image_input_escaped = escapeshellarg('test.png');

    $command = "$path_pngquant --strip -- - < $image_input_escaped";

    // Execute the command
    $handle = popen($command . '2>&1', 'rb'); //MODE : r =read ; b = binary 

    if($handle){
        $output = '';

        while (!feof($handle)) {
            echo $output;
            $output .= fread($handle, 10240); //10240 = 10kb ; read in chunks of 10kb , change it as per need
        }
        fclose($handle);
     
        file_put_contents('test_2.png', $output);
    }

2>&1是在常用shell脚本中使用的redirection syntax

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

https://stackoverflow.com/questions/62668086

复制
相关文章

相似问题

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