Description:
From my android mobile application I am taking a photo with the camera whose Bitmap I encode in Base64 to send it to my .php service which decodes it to save the image on the server.
How do I encode from android:
private fun encodeImage(bm: Bitmap): String? {
val baos = ByteArrayOutputStream()
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos)
val b = baos.toByteArray()
return Base64.encodeToString(b, Base64.DEFAULT)
}
I send the base64 with the name of "productImage"
How to decode from PHP to send to the server
$businessId= $_POST["businessId"];
$productImage = $_POST["productImage"];
$data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $productImage));
/* Nombre del archivo en carpeta */
$path = "productsimgs/"."b$businessId.jpg";
/* Ruta de la imagen (bd) */
$url = "productsimgs/"."b".$businessId.".jpg";
echo json_encode(file_put_contents($path,$data));
Location of my productsimgs folder:
The problem:
When I run the php service, the file_put_contents echo returns "false". Checking my productsimgs folder doesn't save the image. That could be happening?
Assuming you're getting the data correctly and you
$productImage
have the code in Base64, there are two mistakes you're making.relative paths
In the file_put_contents function you are using a relative path . And with this you indicate that the location is in the same folder in which the script is.
If the script is in:
carpeta_proyecto/src/mi_script.php
, then you are telling it to save tocarpeta_proyecto/src/productsimgs/etc...
. And I guess you don't want to have in the same folder as your code the images that will be publicly accessible. I guess .His thing is that you use absolute paths to avoid that problem.
Base64 Decode
The base64_decode function decodes the string and what it returns is in binary format. Your problem is that you use it twice.
You should remove the use of the function in the
file_put_contents
.Another thing
The file_put_contents function returns the number of bytes that were written to the file or
false
otherwise. If after solving the above it continues to indicatefalse
that you have the permissions to write to the folder where you are going to save it.