我有图像的 base 64 数据,我想将它们作为 JPG 文件保存在我的本地机器中。
我的基本 64 代码以
data:image/jpg;base64,/...
我已经尝试通过以下代码保存它:
file_put_contents('MyFile.jpg', base64_decode($imgData1));
但是我无法打开创建的图像; 它说"文件似乎已损坏,损坏或太大"。你能告诉我我错过了什么吗?
另外,如果您需要更多澄清,请让我知道您需要更多澄清的部分。
在调用 base64_decode
之前摆脱 prefex。
<?php
// get rid of everything up to and including the last comma
$imgData1 = substr($imgData1, 1+strrpos($imgData1, ','));
// write the decoded file
file_put_contents('MyFile.jpg', base64_decode($imgData1));
这看起来不仅仅是base64,而是PHP流包装器数据。
file_put_contents('MyFile.jpg', file_get_contents('data:image/jpg;base64,/...'));
你需要
使用imagecreatefromstring
和imagejpeg
,下面是一个例子:
$imageStr = base64_decode($imgData1);
$image = imagecreatefromstring($imageStr);
imagejpeg($image, $somePath);