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
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")
}