Reputation: 2365
I am taking a photograph from within my Android app using this code:
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK){
photo = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 40, baos);
byte[] photoByte = baos.toByteArray();
encodedImage = Base64.encodeToString(photoByte,Base64.DEFAULT);
}
I am sending this String encodedImage
to my PHP server through POST and receiving it to $encodedImage
. I have a database where I have a field myImage
of type MEDIUMBLOB
. I tried to save the encodedimage
in myImage
but it is saved as corrupted image. I tried to save as base64_decode($encodedImage)
but somehow that didn't work either.
I want three things to be done:
Save image to server-side database (BLOB)
Show image to a webpage
Send it back to the Android app.
I am facing issues in understanding the conversion of image required in different formats for the above tasks.
For my current project, I don't want to save my image to folder and give link to the database, so that option is closed for me.
My PHP code to save the image:
$baseImage = $_POST['baseImage'];
$blobImage = base64_decode($baseImage);
$query = "INSERT INTO `complaints`(`myImage`,...) VALUES ('$blobImage',...)"
$result = mysqli_query($conn,$query);
Upvotes: 4
Views: 2668
Reputation: 2883
Prefix your SQL with the keyword _binary"
$query = "INSERT INTO `complaints`
(`myImage`,...)
VALUES (_binary'".addcslashes($blobImage, "\x00\'\"\r\n")."',...)"
Also, setup a test environment with CURL so that you can throw base64 encoded images at it repeatedly. This is going to be a case where you need lots of debugging.
<?php
$f = fopen('sample.jpg.base64.txt', 'w');
$i = fopen('sample.jpg', 'r');
if (!$i) { die("cannot open sample.jpg\n"); }
$bytes = '';
while ( ! feof($i)) {
$bytes .= fread($i, 4096);
}
fclose($i);
fputs($f, base64_encode( $bytes ) );
fclose($f);
And then use curl to post it repeatedly and debug your PHP
curl -X PUT "http://localhost/myimport.php" -F "baseImage=@./sample.jpg.base64.txt"
Adjust your PHP script to simply write out the data to a file on your hard drive and inspect it there. Write out multiple versions, both encoded and decoded.
Personally, I wouldn't base64 the bytes going from Android to PHP, but I would base64 encode them in mysql.
Upvotes: 1
Reputation: 7805
Do not decode your image in PHP, store it as you receive it, Now, in frontend you can print the image as follow
<?php
$img = '<img src="data:image/jpeg;base64,' . $encodedImgStoredInDB . '">';
print $img;
?>
Upvotes: 3