java 旋转 png base64_如何从base64数据字符串保存PNG映像服务器端

回答(12)

e15298c6a3b4591803e154ab0c3b3e2e.png

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);

e15298c6a3b4591803e154ab0c3b3e2e.png

2 years ago

那么你的解决方案取决于图像是一个jpeg文件 . 对于我使用的一般解决方案

$img = $_POST['image'];

$img = substr(explode(";",$img)[1], 7);

file_put_contents('img.png', base64_decode($img));

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值