Skip to content

Commit 22091ca

Browse files
committed
Fix related to image format
1 parent a9c5533 commit 22091ca

File tree

1 file changed

+15
-3
lines changed

1 file changed

+15
-3
lines changed

lib/src/main/java/com/sonsation/image_compressor/Compression.kt

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ import java.io.File
1616

1717
class Compression(val context: Context) {
1818

19-
var format: Bitmap.CompressFormat = Bitmap.CompressFormat.JPEG
19+
var format: Bitmap.CompressFormat? = null
2020
var maxWidth = 0
2121
var maxHeight = 0
2222
var quality = 100
@@ -32,7 +32,9 @@ class Compression(val context: Context) {
3232

3333
val imageFile = getInputFile()
3434

35-
format = imageFile.getImageFormat(context)
35+
if (format == null) {
36+
format = imageFile.getImageFormat(context)
37+
}
3638

3739
val sampledBitmap = if (maxWidth != 0 || maxHeight != 0) {
3840
val reqWidth = maxWidth.times(scale).toInt()
@@ -51,8 +53,18 @@ class Compression(val context: Context) {
5153
}
5254

5355
bitmap.use {
54-
it.toByteArray(format, quality)
56+
it.toByteArray(format!!, quality)
5557
}.write(imageFile)
58+
59+
val extension = when (format!!) {
60+
Bitmap.CompressFormat.PNG -> "png"
61+
Bitmap.CompressFormat.JPEG -> "jpeg"
62+
else -> "webp"
63+
}
64+
65+
File("${imageFile.absolutePath}.${extension}").apply {
66+
imageFile.renameTo(this)
67+
}
5668
} catch (e: Exception) {
5769
Log.e("ImageCompressor", "Error while compressing image : ${e}")
5870
throw NullPointerException("Compressed image is null")

0 commit comments

Comments
 (0)