您需要从该字符串中提取base 64映像数据,对其进行解码,然后可以将其保存到磁盘中,您不需要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);