PHP处理base64图片
写入文件
$img = "data:image/png;base64,......";
preg_match('/^data:\s*(image\/)(\w+);base64,/', $img, $m);
$img = preg_replace('/^data:\s*image\/\w+?;base64,/', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$filename = 'test.' . $m[2];
$contentType = $m[1];
$path = __DIR__ . "/" . $filename;
$fp = fopen($path, 'w');
fwrite($fp, $data);
fclose($fp);
$file_size=filesize($path);
header('HTTP/1.1 200 OK');
Header("Content-type: " . $contentType);
Header("Accept-Length:".$file_size);
readfile($imgPath);
下载图片
Header("Content-Disposition: attachment; filename=test.png");
$img = "data:image/png;base64,......";
preg_match('/^data:\s*(image\/)(\w+);base64,/', $img, $m);
$img = preg_replace('/^data:\s*image\/\w+?;base64,/', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$filename = 'test.' . $m[2];
$contentType = $m[1];
Header("Content-type: image/png");
Header("Content-Disposition: attachment; filename=test.png");
$fp = fopen('php://output', 'w');
fwrite($fp, $data);
fclose($fp);
|