[英]pngquant and shell_exec checking status code and then saving image
我有以下代碼似乎正在生成損壞的圖像。 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);
}
exec會弄亂二進制 stream 你需要的是打開 output stream 從它讀取二進制模式。 幸運的是, 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 腳本中使用的重定向語法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.