Search code examples
androidkotlincamerabase64

How to convert bitmap image to base64 without losing image quality android


    ivPersonImageA.setOnClickListener {
        val mIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        startActivityForResult(
            mIntent,
            PERSON_CODE
        )
    }


@Deprecated("Deprecated in Java")
override  fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (requestCode == PERSON_CODE) {
        if (resultCode == RESULT_OK) {
            val  imageBitmap = data?.extras?.get("data") as Bitmap
            personAvImageA.setImageBitmap(imageBitmap)
            mPesrsonBase64 = encodeImage(imageBitmap)
            Log.e("mPersonBase64", mPesrsonBase64)
        }
    }
}




private fun encodeImage(bitmap: Bitmap): String {
    val previewWidth = 150
    val previewHeight = bitmap.height * previewWidth / bitmap.width
    val previewBitmap = Bitmap.createScaledBitmap(bitmap, previewWidth, previewHeight, false)
    val byteArrayOutputStream = ByteArrayOutputStream()
    previewBitmap.compress(Bitmap.CompressFormat.JPEG, 70, byteArrayOutputStream)
    val bytes = byteArrayOutputStream.toByteArray()
    return Base64.encodeToString(bytes, Base64.CRLF)
}

This is all my code when I run my code and I checked my run box there I got basee64 path after that check that path on website but there I lost my image quality and this also same problem with server


Solution

  • The original bitmap is the pure image data, and you can convert that to (a lot of) Base64 with no loss - it's just another way of representing the same data. But resizing the bitmap is throwing away data, and so is compressing it to JPEG (especially at 70% quality).

    You're calling that smaller version preview anyway, are you sure that's the data you care about? Previews are usually smaller/less detailed, that's the point! Honestly you probably just either use a much higher quality level for the JPEG compression (90 or 95) or better yet, use Bitmap.CompressFormat.PNG if you can. That's a lossless format, and it'll have better quality especially on non-photographic content - the file size will be bigger, but for such a small image it probably won't make much difference.

    Also you're calling createScaledBitmap with filtering set to false. Filtering is what blends the pixels to resize things with better quality, it's especially important for shrinking things down at an arbitrary ratio. Set that to true and it'll look a lot better.

    Bitmap.createScaledBitmap(bitmap, previewWidth, previewHeight, true)