pngquant and shell_exec checking status code and then saving image

187 Views Asked by At

I have the following code that seems to be generating a corrupted image. Photoshop says "PNG file corrupted by ASCII conversion"

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

1

There are 1 best solutions below

2
Vinay On

exec will mess up the binary stream what you need is to open the output stream in binary mode read from it. Luckily popen is just for that

    <?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 is redirection syntax used in common shell scripts