-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathImageCompressor.kt
More file actions
59 lines (55 loc) · 2.21 KB
/
Copy pathImageCompressor.kt
File metadata and controls
59 lines (55 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package com.smith.imagecompressor.utils
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import java.io.File
import java.io.FileOutputStream
import kotlin.math.min
object ImageCompressor {
/**
* This doesn't compress the original image file.
* It compresses the bitmap and updates it to the new file and returns from app cache
*/
@Throws(Exception::class)
fun compressBitmap(context: Context, originalImageFile: File, cb: ((File) -> Unit)? = null) {
val bitmap = updateDecodeBounds(originalImageFile)
val file = context.getPicturesFile(originalImageFile.name)
val fOut = FileOutputStream(file)
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fOut)
fOut.flush() // Not really required
fOut.close() // do not forget to close the stream
bitmap.recycle() //recycle the bitmap
cb?.invoke(file)
}
/**
* This compress the original file.
*/
@Throws(Exception::class)
fun compressCurrentBitmapFile(originalImageFile: File) {
val bitmap = updateDecodeBounds(originalImageFile)
val fOut = FileOutputStream(originalImageFile)
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fOut)
fOut.flush() // Not really required
fOut.close() // do not forget to close the stream
bitmap.recycle() //recycle the bitmap
}
/**
* Measure decodeBounds of the bitmap from given File.
*/
private fun updateDecodeBounds(imageFile: File): Bitmap {
return BitmapFactory.Options().run {
inJustDecodeBounds = true
BitmapFactory.decodeFile(imageFile.absolutePath, this)
val sampleHeight = if (outWidth > outHeight) 900 else 1100
val sampleWidth = if (outWidth > outHeight) 1100 else 900
/**
* You can tweak the sizes 900, 1100.
* The bigger the number is, the more details you can keep.
* The lesser, the lesser quality of details.
*/
inSampleSize = min(outWidth / sampleWidth, outHeight / sampleHeight)
inJustDecodeBounds = false
BitmapFactory.decodeFile(imageFile.absolutePath, this)
}
}
}