Skip to content Skip to sidebar Skip to footer

How To Compress Photo In Android With Kotlin

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 Executio

Solution 1:

Use Compressor

Gradle

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

Compress Image File

valcompressedImageFile= Compressor.compress(context, actualImageFile)

Compress Image File to specific destination

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

Using default constraint and custom partial of it

valcompressedImageFile= 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
}

Solution 2:

Use Resizer

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

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

FileresizedImage=newResizer(this)
    .setTargetLength(1080)
    .setQuality(80)
    .setOutputFormat("JPEG")
    .setOutputFilename("resized_image")
    .setOutputDirPath(storagePath)
    .setSourceImage(originalImage)
    .getResizedFile();

Solution 3:

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 bitmapval bitmap = Compressor(this).compressToBitmap(rutaFinal)

//if you need fileval 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 Compressorval bitmap = Compressor(this).compressToBitmap(rutaFinal);


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

    }

Post a Comment for "How To Compress Photo In Android With Kotlin"