DEV Community

loizenai
loizenai

Posted on

Kotlin – Encode (Decode) File/Image to Base64

Kotlin – Encode (Decode) File/Image to Base64

https://grokonez.com/kotlin/kotlin-encode-decode-fileimage-base64

For some purpose like transfering an image through RestfulAPI or saving an image to a DataBase, We need Encoder (Decode) the image to Base64. In the tutorial, JavaSampleApproach will guide you how to use Kotlin language for converting.

Note: Prepare an Image at folder 'C:\base64\image.jpg'

I. Kotlin Encode File/Image to Base64


fun encoder(filePath: String): String{
    val bytes = File(filePath).readBytes()
    val base64 = Base64.getEncoder().encodeToString(bytes)
    return base64
}

II. Kotlin Decode Base64 to File/Image


fun decoder(base64Str: String, pathFile: String): Unit{
    val imageByteArray = Base64.getDecoder().decode(base64Str)
    File(pathFile).writeBytes(imageByteArray)
}

III. Full Sample

More at:

Kotlin – Encode (Decode) File/Image to Base64

https://grokonez.com/kotlin/kotlin-encode-decode-fileimage-base64

Top comments (0)