How to save a JPEG image on Android with a custom quality level

后端 未结 4 1331
滥情空心
滥情空心 2020-12-01 11:47

On Android, how do I save an image file as a JPEG at 30% quality?

In standard Java, I would use ImageIO to read the image as a BufferedImage

4条回答
  •  爱一瞬间的悲伤
    2020-12-01 12:11

    Using Kotlin to save a file in path to tmpPath:

    Files.newInputStream(path).use { inputStream ->
        Files.newOutputStream(tmpPath).use { tmpOutputStream ->
            BitmapFactory
                .decodeStream(inputStream)
                .compress(Bitmap.CompressFormat.JPEG, 30, tmpOutputStream)
        }
    }
    

    Edit: make sure you check for the possibility of the decode failing (and returning null) and also that compress actually worked (boolean return type).

        val success: Boolean = Files.newInputStream(path).use { inputStream ->
            Files.newOutputStream(tmpPath).use { tmpOutputStream ->
                BitmapFactory
                    .decodeStream(inputStream)
                    ?.compress(Bitmap.CompressFormat.JPEG, config.qualityLevel, tmpOutputStream)
                    ?: throw Exception("Failed to decode image")
            }
        }
    
        if (!success) {
            throw Exception("Failed to compress and save image")
        }
    

提交回复
热议问题