🛠️ Optimize Image compression
* Dynamic image compression based on file size (slightly reduces memory consumption)
This commit is contained in:
parent
c3e94931aa
commit
ef0450ecf2
1 changed files with 40 additions and 17 deletions
|
|
@ -106,27 +106,13 @@ class DocumentParser @Inject constructor(
|
||||||
src == image.name.substringAfterLast('/').lowercase()
|
src == image.name.substringAfterLast('/').lowercase()
|
||||||
} ?: return@forEach
|
} ?: return@forEach
|
||||||
|
|
||||||
zipFile?.getInputStream(imageEntry)?.use { inputStream ->
|
zipFile?.getImage(imageEntry)?.asImageBitmap()
|
||||||
val options = BitmapFactory.Options().apply {
|
|
||||||
inSampleSize = 2
|
|
||||||
inPreferredConfig = Bitmap.Config.RGB_565
|
|
||||||
}
|
|
||||||
BitmapFactory.decodeStream(
|
|
||||||
/* is = */ inputStream,
|
|
||||||
/* outPadding = */ null,
|
|
||||||
/* opts = */ options
|
|
||||||
)?.asImageBitmap()
|
|
||||||
}
|
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
e.printStackTrace()
|
e.printStackTrace()
|
||||||
return@forEach
|
null
|
||||||
}
|
} ?: return@forEach
|
||||||
|
|
||||||
if (image == null) return@forEach
|
|
||||||
|
|
||||||
// Optimize
|
|
||||||
image.prepareToDraw()
|
image.prepareToDraw()
|
||||||
|
|
||||||
readerText.add( // Adding image
|
readerText.add( // Adding image
|
||||||
ReaderText.Image(
|
ReaderText.Image(
|
||||||
imageBitmap = image
|
imageBitmap = image
|
||||||
|
|
@ -178,4 +164,41 @@ class DocumentParser @Inject constructor(
|
||||||
|
|
||||||
return readerText
|
return readerText
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Getting bitmap from [ZipFile] with compression
|
||||||
|
* that depends on the [imageEntry] size.
|
||||||
|
*/
|
||||||
|
private fun ZipFile.getImage(imageEntry: ZipEntry): Bitmap? {
|
||||||
|
fun getBitmapFromInputStream(compressionLevel: Int = 1): Bitmap? {
|
||||||
|
return getInputStream(imageEntry).use { inputStream ->
|
||||||
|
BitmapFactory.decodeStream(
|
||||||
|
inputStream,
|
||||||
|
null,
|
||||||
|
BitmapFactory.Options().apply {
|
||||||
|
inPreferredConfig = Bitmap.Config.RGB_565
|
||||||
|
inSampleSize = compressionLevel
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
val uncompressedBitmap = getBitmapFromInputStream() ?: return null
|
||||||
|
return when (uncompressedBitmap.byteCount) {
|
||||||
|
in 0..1048576 /* 0 - 1MB */ -> {
|
||||||
|
uncompressedBitmap
|
||||||
|
}
|
||||||
|
|
||||||
|
in 1048576..2097152 /* 1MB - 2MB */ -> {
|
||||||
|
uncompressedBitmap.recycle()
|
||||||
|
getBitmapFromInputStream(2)
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> /* >=2MB */ {
|
||||||
|
uncompressedBitmap.recycle()
|
||||||
|
getBitmapFromInputStream(3)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue