Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save hosseiniSeyRo/90a150eeb59cc19bd1f96c40f9cf4dd2 to your computer and use it in GitHub Desktop.
Save hosseiniSeyRo/90a150eeb59cc19bd1f96c40f9cf4dd2 to your computer and use it in GitHub Desktop.
convert image to base64
fun convertImageToBase64(imageFile: File): String {
return ByteArrayOutputStream().use { outputStream ->
Base64OutputStream(outputStream, Base64.DEFAULT).use { base64FilterStream ->
imageFile.inputStream().use { inputStream ->
inputStream.copyTo(base64FilterStream)
}
}
return@use outputStream.toString()
}
}
fun convertImageToBase64(path: String): String {
try {
val imageFile = File(path)
var fis: FileInputStream? = null
try {
fis = FileInputStream(imageFile)
} catch (e: FileNotFoundException) {
e.printStackTrace()
}
val bm = BitmapFactory.decodeStream(fis)
val baos = ByteArrayOutputStream()
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos)
val b = baos.toByteArray()
return Base64.encodeToString(b, Base64.DEFAULT)
} catch (e: Exception) {
return ""
}
}
fun convertImageToBase64(uri: Uri): String {
try {
val imageStream: InputStream = getContentResolver().openInputStream(uri)
val bm = BitmapFactory.decodeStream(imageStream)
val baos = ByteArrayOutputStream()
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos)
val b = baos.toByteArray()
return Base64.encodeToString(b, Base64.NO_WRAP)
} catch (e: Exception) {
return ""
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment