Issue
I need to save an image from the Client App as PNG on the Backend. Im sending the Image as Base64 with Post to the Backend. I cant find a way to convert the Base64 String to an PNG File and dont know, how I could save them as File on the Server.
Thats the function I use to get the Data from the client. In val picture I get the Image as Base64.
fun savepicture(data: getpicture) =
transaction {
val userid= data.userid
val date = data.date
val time = data.time
val picture= data.picture
println("$picture")
try {
decodeImage(aufnahme)
}
catch(e: Exception) {
println("Fehler: $e")
}
if (picture.isNotEmpty()) {
return@transaction true
}
return@transaction false
}
fun decodeImage(image: String) {
val pictureBytes = Base64.getDecoder().decode(image)
val path = Path("Path/to/destination")
path.writeBytes(pictureBytes)
}
With this function i create the Base64 String. The Bitmap is created of a picture taken form the Device.
fun encodeImage(bm: Bitmap): String? {
val baos = ByteArrayOutputStream()
bm.compress(Bitmap.CompressFormat.PNG, 90, baos)
val b = baos.toByteArray()
return java.util.Base64.getEncoder().encodeToString(b)
}
I hope someone could help me to convert and save my image.
Solution
You can use java.util.Base64
to decode your base64 string into bytes. Then you'll need to write the bytes into a file.
For instance:
val picture: String = "the base64 data here as a string"
// decode the base64 text into bytes
val pictureBytes = Base64.getDecoder().decode(picture)
// write the bytes to a file
val path = Path("the/path/to/the/file.png")
path.writeBytes(pictureBytes)
Answered By - Joffrey
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.