回答(12)
2 years ago
您需要从该字符串中提取base64图像数据,对其进行解码然后将其保存到磁盘,您不需要GD,因为它已经是png .
$data = 'data:image/png;base64,AAAFBfj42Pj4';
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);
file_put_contents('/tmp/image.png', $data);
作为一个单行:
$data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $data));
提取,解码和检查错误的有效方法是:
if (preg_match('/^data:image\/(\w+);base64,/', $data, $type)) {
$data = substr($data, strpos($data, ',') + 1);
$type = strtolower($type[1]); // jpg, png, gif
if (!in_array($type, [ 'jpg', 'jpeg', 'gif', 'png' ])) {
throw new \Exception('invalid image type');
}
$data = base64_decode($data);
if ($data === false) {
throw new \Exception('base64_decode failed');
}
} else {
throw new \Exception('did not match data URI with image data');
}
file_put_contents("img.{$type}", $data);
2 years ago
那么你的解决方案取决于图像是一个jpeg文件 . 对于我使用的一般解决方案
$img = $_POST['image'];
$img = substr(explode(";",$img)[1], 7);
file_put_contents('img.png', base64_decode($img));