我正在从我的 Android 应用程序向 PHP 发送 base64
编码图像。有时它存储完整图像(4KB),有时存储(3KB)(同一图像)。当我在 picasso 中使用 URL 时,4KB 大小的图像工作正常,但 3KB 大小的图像无法加载,它显示解码错误。
这是我的 PHP 代码(有时可以工作)
$encodedImage = str_replace(' ','+',$_POST['encodedProfileImage']);
$data = base64_decode($encodedImage);
$file = 'Pics/'. uniqid() . '.png';
$success = file_put_contents($file, $data);
$BASE_URL = 'http://domain.com/TestApp/';
然后我在 PHP 中执行 SQL 操作来存储图像路径。下一个代码操作是否有可能在半解码图像(已损坏)上完成。
最佳答案
您需要删除图像数据开头的 data:image/png;base64
部分。实际的 Base64 数据随后出现。
使用以下功能:-
function base64_to_png($base64_string, $output_file) {
$ifp = fopen($output_file, "wb");
$data = explode(',', $base64_string);
fwrite($ifp, base64_decode($data[1]));
fclose($ifp);
return $output_file;
}
如果您想使用str_replace
函数,则可能按以下方式工作。我不确定:)
$fname = filter_input(INPUT_POST, "name");
$encodedImage = filter_input(INPUT_POST, "image");
$encodedImage = str_replace('data:image/png;base64,', '', $encodedImage);
$encodedImage = str_replace(' ', '+', $encodedImage);
$encodedImage = base64_decode($encodedImage);
file_put_contents($fname, $encodedImage);
print "Image has been saved!";
希望对你有帮助:)
关于PHP base64_decode 保存损坏的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35473757/