0

我有以下代码似乎正在生成损坏的图像。Photoshop 显示“PNG 文件因 ASCII 转换而损坏”

    $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);
    }

4

1 回答 1

0

exec会弄乱二进制流,您需要以二进制模式打开输出流,从中读取。幸运的是, popen就是为了这个

    <?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脚本中使用的重定向语法

于 2020-07-01T03:33:34.633 回答