解码从Android发布的Base64图像数据,以将图像保存在PHP服务器上


decode base64 image data posted from android to save image on php server

>我正在开发一个网络服务,使用 php 脚本将图像从安卓设备上传到服务器,其中 base64 字符串形式的图像数据使用 http post 请求从安卓设备发送到服务器。在服务器端,我使用以下代码解码图像数据并将图像保存到服务器:

$json = file_get_contents('php://input');
$obj = json_decode($json);
$base = $obj->image;
$ext = $obj->extension;
$folderPath = "./logo/";
$fileName = 'logo_'.$time.'.'.$ext;
$binary = bin2hex(base64_decode($base));
$data = pack("H" . strlen($binary), $binary);
$file = fopen($folderPath.$fileName, 'wb');
fwrite($file, $data);
fclose($file);

此代码正在服务器上保存图像数据,但图像数据与android应用程序发布的数据不同。甚至上传文件的大小也与原始文件不匹配。
那么任何人都可以帮助我,以便从android应用程序发送的图像数据正确解码并保存在与从android发送的图像相同的图像文件中?

我解决了这个问题。问题是由于服务器在接收的图像数据中插入了额外的字符。在服务器上,当发布任何字符串时,php 服务器将 + 符号视为空格,因此它会为此插入一些额外的字符。此外,它还替换了服务器上接收的图像数据中的其他一些字符,例如 = 和/符号,替换为一些以 % 符号开头的值。由于图像数据中的这些额外字符,base64_decode函数无法正确解码 base64 为二进制。我通过使用 php 的 urldecode 函数解决了这个问题。现在我的工作代码是:


$newBase = urldecode($base);
$binary = base64_decode($newBase);
$file = fopen($folderPath.$fileName, 'wb');
fwrite($file, $binary); fclose($file);

现在,正在服务器上上传正确的图像。