You need to extract the base64 image data from that string, decode it and then you can save it to disk, you don't need GD since it already is a png.(您需要从该字符串中提取base64图像数据,对其进行解码,然后可以将其保存到磁盘,因为它已经是png,所以不需要GD。)
$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);
And as a one-liner:(作为单线:)
$data = base64_decode(preg_replace('#^data:image/w+;base64,#i', '', $data));
An efficient method for extracting, decoding, and checking for errors is:(提取,解码和检查错误的有效方法是:)
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);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…