How to compress photo in Android with Kotlin-ThrowExceptions

Exception or error:

now this is my code to take a photo from my smartphone, the problem is that the image is very large and I would like to compress it, some help or idea?

thanks for the info

Execution of the method abrirCamara()

private fun abrirCamara() {
    val values = ContentValues()
    values.put(MediaStore.Images.Media.TITLE, "Nueva foto")
    values.put(MediaStore.Images.Media.DESCRIPTION, "Desde la camara")
    image_uri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)
    //intención de la cámara
    val cameraIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri)
    startActivityForResult(cameraIntent, IMAGE_CAPTURE_CODE)

}

is called when the user press PERMIT or DENY from the permission request pop-up window

override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {

    when(requestCode){
        PERMISSION_CODE -> {
            if (grantResults.size > 0 && grantResults[0] ==
                PackageManager.PERMISSION_GRANTED){
                //permiso de popup fue concedido
                abrirCamara()
            }
            else{
                //el permiso de popup fue denegado
                Toast.makeText(this, "Permiso denegado", Toast.LENGTH_SHORT).show()
            }
        }
    }
}

Call when the image was captured from the camera’s intention

     override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    //Llamada cuando la imagen fue capturada desde la intención de la cámara
    if (resultCode == Activity.RESULT_OK){


        //configurar imagen capturada a vista de imagen (ImageView)
        imgEnvio.setImageURI(image_uri)        

        captura_btn.visibility =View.INVISIBLE
        siguiente.visibility=View.VISIBLE

    }
}
How to solve:

Use Compressor

Gradle

dependencies {
implementation 'id.zelory:compressor:3.0.0'
}

Compress Image File

val compressedImageFile = Compressor.compress(context, actualImageFile)

Compress Image File to specific destination

val compressedImageFile = Compressor.compress(context, actualImageFile) {
default()
destination(myFile)
}

Using default constraint and custom partial of it

val compressedImageFile = Compressor.compress(context, actualImageFile) {
default(width = 640, format = Bitmap.CompressFormat.WEBP)
}

Full custom constraint

val compressedImageFile = Compressor.compress(context, actualImageFile) {
resolution(1280, 720)
quality(80)
format(Bitmap.CompressFormat.WEBP)
size(2_097_152) // 2 MB
}

val compressedImageFile = Compressor.compress(context, actualImageFile) {
    resolution(1280, 720)
    quality(80)
    format(Bitmap.CompressFormat.WEBP)
    size(2_097_152) // 2 MB
    }

val compressedImageFile = Compressor.compress(context, actualImageFile) {
    resolution(1280, 720)
    quality(80)
    format(Bitmap.CompressFormat.WEBP)
    size(2_097_152) // 2 MB
    }

val compressedImageFile = Compressor.compress(context, actualImageFile) {
    resolution(1280, 720)
    quality(80)
    format(Bitmap.CompressFormat.WEBP)
    size(2_097_152) // 2 MB
}

###

You can use this library

implementation 'id.zelory:compressor:2.1.0'

change the code

from your code, your image file name is rutaFinal

//if you need bitmap
val bitmap = Compressor(this).compressToBitmap(rutaFinal)

//if you need file
val compressedImageFile = Compressor(this).compressToFile(rutaFinal)

complete code

 if (resultCode == Activity.RESULT_OK){


        //configurar imagen capturada a vista de imagen
        imgEnvio.setImageURI(image_uri)
        pasar = image_uri.toString()


        val tempUri = image_uri

        val rutaFinal = File(getRealPathFromURI(tempUri))
        pasoRuta=rutaFinal.toString()

        //chnage here
        //pass context to Compressor
        val bitmap = Compressor(this).compressToBitmap(rutaFinal);


        captura_btn.visibility =View.INVISIBLE
        siguiente.visibility=View.VISIBLE

    }

Hope this answer will help you

###

Use Resizer

compile 'com.github.hkk595:Resizer:v1.5'

Pass in the original image file and get the resized image as a new file

File resizedImage = new Resizer(this)
    .setTargetLength(1080)
    .setQuality(80)
    .setOutputFormat("JPEG")
    .setOutputFilename("resized_image")
    .setOutputDirPath(storagePath)
    .setSourceImage(originalImage)
    .getResizedFile();

Leave a Reply

Your email address will not be published. Required fields are marked *