私の関数では、base64文字列からデコードされた画像を保存しています。
function saveImage(){
//magic...
define('UPLOAD_DIR', '../webroot/img/');
$base64string = str_replace('data:image/png;base64,', '', $base64string);
$base64string = str_replace(' ', '+', $base64string);
$data = base64_decode($base64string);
$id = uniqid();
$file = UPLOAD_DIR.$id.'.png';
$success = file_put_contents($file, $data);
}
上記の機能は正常に動作し、画像は指定されたフォルダに保存され、破損しません。
次の関数では、画像をユーザーに強制的にダウンロードしようとしています。
function getChart($uniqid= null){
if($uniqid){
$this->layout = null;
header("Content-type: image/png");
header("Content-Disposition:attachment;filename='".$uniqid.".png'");
readfile('../webroot/img/'.$uniqid.'.png');
exit;
} else exit;
}
サーバーからダウンロードした画像が破損していて表示できません。ダウンロードしたファイルをテキストエディタで開いた後、一番上に改行文字が追加されていることに気づきました。文字を削除してファイルを保存すると、文字が正しく開き、正しく表示されます。
どうすればこれを修正できますか?