zetbaitsu / Compressor

An android image compression library.
7.08k stars 963 forks source link

Compress big png image always fail #174

Open XuQK opened 3 years ago

XuQK commented 3 years ago

I have a big png image, my code is :

Compressor.compress(App.instance, file) {
                destination(
                    File(
                        cacheImageDir,
                        compressedFileName
                    )
                )
                size(1024 * 1024 * 10)
            }

The result is always bad, sometimes it big as the original, sometimes it is broken.

You can get the file from here: https://drive.google.com/file/d/1tfAd1sMrQ0IfNb2xFKIuAburfMzhQijH/view?usp=sharing

meyerhp commented 3 years ago

I ran into a similar issue and I found that if you use the size constraint the library incrementally compresses the file until it reaches the target size instead of just calculating the expected quality (see below)

override fun satisfy(imageFile: File): File {
        iteration++
        val quality = (100 - iteration * stepSize).takeIf { it >= minQuality } ?: minQuality
        return overWrite(imageFile, loadBitmap(imageFile), quality = quality)
    }

To speed up compression use the quality constraint instead, it will only compress the file once. If you still want to use size as a constraint I would recommend doing something like this.

val targetSize = 1024 * 1024 * 10
val targetQuality = targetSize / file.length() * 100
val minQuality = min(targetQuality, 90.0)
Compressor.compress(context, file) {
     quality(minQuality.toInt())
     format(Bitmap.CompressFormat.JPEG)
}
azizhudai commented 2 years ago

This solution worked for me.

Add these lines in your Manifest application tag

android:largeHeap="true" android:hardwareAccelerated="false"

https://stackoverflow.com/questions/40835514/android-canvas-drawing-too-large-bitmap