Resize the image programmatically using kotlin in Android

Tausif Uddin Ahmed
2 min readOct 23, 2020

We all need to show image in UI or upload image in server some times in android app development.

Very often the image size is so big that we can't show in the UI. It shows error something like -”java.lang.RuntimeException: Canvas: trying to draw too large(137414032bytes) bitmap.”

We also face the issue to upload the image in the server in base64 format. Especially when we send the encoded base64 image in field parameter as a string to post request. It shows the following error — “413 Request entity is too large “

To overcome the issue, We can resize the image before showing to UI or uploading the server if the image quality is not an issue. Let’s do this.

First, we take the selected image URI chosen from the gallery or taken from camera. This part is not given here.

private lateinit var selectedImageBitMap: Bitmap
private lateinit var imageInBitMapAfterResize: Bitmapprivate private lateinit var imageViewProfileImage: ImageView
private val baos = ByteArrayOutputStream()
const val PREFERRED_IMAGE_SIZE = 400 //400kb
const val ONE_MB_TO_KB = 1024

// here selected image = image URI from gallay/cameraval
imageStream: InputStream = selectedImage?.let {
context?.contentResolver?.openInputStream(
it
)
}!!

selectedImageBitMap = BitmapFactory.decodeStream(imageStream)

selectedImageBitMap.compress(Bitmap.CompressFormat.JPEG, 50, baos)
//if compressed picture is greater than 400kb, than to reduce sizeif (baos.toByteArray().size / ONE_MB_TO_KB > PREFERRED_IMAGE_SIZE) {

//resize photo & set Image in imageview In UI
imageInBitMapAfterResize=resizePhoto(selectedImageBitMap)
imageViewProfileImage.setImageBitmap(imageInBitMapAfterResize)

}

In the above code, ByteArrayOutputStream object is declared to store the image in byte array.First, Image is taken as imageStream(InputStream) from image selectedImage(URI).Then decode & compress this imageStream(InputStream) using bitmap(selectedImageBitMap) and keep it in baos(ByteArrayOutputStream.)

Then compare the image size with our required size. If the size is bigger than the required size we will resize the image using resizePhoto() function, otherwise, keep it as it is.

Here is resizePhoto() function

fun resizePhoto(bitmap: Bitmap): Bitmap {


val w = bitmap.width
val h = bitmap.height
val aspRat = w / h
val W = 400
val H = W * aspRat
val b = Bitmap.createScaledBitmap(bitmap, W, H, false)

return b


}

That’s all.

--

--