Amrinder Singh
Amrinder Singh

Reputation: 215

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

I am developing a web service to upload image from android device to server using php script where image data in the form of base64 string is sent from android device to server using http post request. And at server end I am using following code to decode image data and save image to the server:

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

This code is saving image data on the server but image data is not same as data posted by android application. Even size of uploaded file does not match with original file.
So can anyone help me in this so that image data sent from android application decoded properly and saved in image file same as image sent from android?

Upvotes: 1

Views: 3662

Answers (1)

Amrinder Singh
Amrinder Singh

Reputation: 215

I resolved this issue. Issue was due to extra characters inserted in the received image data by server. On server when any string is posted, php server consider + sign as space and so it inserts some extra characters for this. Also it was replacing some other characters in the image data received on the server like = and / signs were replaced by some values started with % sign. And due to these extra characters in the image data, base64_decode function was not decoding base64 to binary properly. I resolved this issue by using urldecode function of php. Now my working code is:

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

Now correct image is being uploaded on the server.

Upvotes: 1

Related Questions