【问题标题】:pngquant and shell_exec checking status code and then saving imagepngquant 和 shell_exec 检查状态码然后保存图像
【发布时间】:2020-10-21 09:14:06
【问题描述】:

我的以下代码似乎正在生成损坏的图像。 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);
    }

【问题讨论】:

  • 你怎么知道$output是有效的图像数据?你甚至从不使用$image_input_escaped。更不用说您的 $command 似乎未定义。
  • 抱歉,这是一个复制粘贴错误。我省略了运行命令的部分,命令运行并创建了一个无法打开的 40kb png。
  • 小于号的用途是什么?这是pngquant 的哪个版本?
  • 我问是因为我刚刚使用 pngquant 进行了一些自动 png 压缩,并重复自动缩减。但与您的方法不同,我有一个控制台 php 脚本创建一个批处理(在 Windows 中为 *.bat 或 *.cmd ...)在连续重命名结果输出后执行该操作。没有看到小于登录的帮助文档。这是一个“linux”开关吗?

标签: php png pngquant


【解决方案1】:

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>&1redirection syntax 用于常见的shell 脚本

【讨论】:

  • 二进制流被弄乱了,这很有意义。但是有一个问题,在我的原始文件中,我检查 if($status_code == 0) 是否有任何方法可以使用 popen 读取状态代码?
  • 是的情况下出现错误$handle 将设置为 false
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-25
  • 2014-01-24
  • 2012-12-22
  • 2013-01-15
  • 1970-01-01
  • 2017-05-24
相关资源
最近更新 更多