How To Convert An Image Into Base64 And Also Compress It Using Kotlin In Androidx?
I am creating an offline SMS app. I want to know how to convert image, chosen by the user, into string base64 and also compressed it. I have searched a lot but not much material I
Solution 1:
If condition because it needs build version 26. Below version it won't work
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
valbm= BitmapFactory.decodeFile("/path/to/image.jpg")
valstream= ByteArrayOutputStream()
bm.compress(CompressFormat.JPEG, 70, stream)
valbyteFormat= stream.toByteArray()
valimgString= Base64.getEncoder().encodeToString(byteFormat)
}
To Retrieve the Path/to/Image :
val uri = data!!.dataval picturePath = getPath(applicationContext, uri) // Write this line under the uri.
Log.d("Picture Path", picturePath)
This is function to get the path of Image.
privatefungetPath(applicationContext: Context, uri: Uri?): String? {
var result: String? = nullval proj = arrayOf(MediaStore.Images.Media.DATA)
val cursor = applicationContext.getContentResolver().query(uri, proj, null, null, null)
if (cursor != null) {
if (cursor!!.moveToFirst()) {
val column_index = cursor!!.getColumnIndexOrThrow(proj[0])
result = cursor!!.getString(column_index)
}
cursor!!.close()
}
if (result == null) {
result = "Not found"
}
return result
}
Solution 2:
In Kotlin, To convert your Image File to Base64 and then compress it
valbm= BitmapFactory.decodeFile("/path/to/image.jpg")
valbaos= ByteArrayOutputStream()
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos) //bm is the bitmap objectvalb= baos.toByteArray()
valencodedImage= Base64.encodeToString(b, Base64.DEFAULT)
You have to replace your image path in the first line.
Post a Comment for "How To Convert An Image Into Base64 And Also Compress It Using Kotlin In Androidx?"