Huffman algorithm
-
Huffman algorithm is also a lossless compression algorithm, but different from LZW compression algorithm, Huffman needs to obtain prior knowledge of the occurrence probability of each character. By calculating the frequency of each character in the character sequence, unique coding design is carried out for each character, so that the characters with high frequency occupy a short bit, and the characters with low frequency are long, to achieve the purpose of compression. Typically 20% to 90% of the space can be saved, largely depending on the nature of the data! Huffman encoding is variable-length encoding, that is, the encoding length of each character is not unique.
-
Prefix code: The encoding of any character is not the prefix of another character encoding in the same character set. Huffman coding is the optimal prefix code, that is, the minimum amount of data after compression.
Step 1. Add the JitPack repository to your build file
Add it in your root build.gradle at the end of repositories:
allprojects {
repositories {
...
maven { url 'https://jitpack.io' }
}
}
Copy the code
Step 2. Add the dependency
Dependencies {implementation 'com. Making. Ewgcat: CompressImageByHuffman: 1.0.6'}Copy the code
Class BaseViewModel: ViewModel() {/** * Can't complete the main line of the hard operation */ fun compressImage(path: String? , quality: IntArray, totalSize: Int, desPath: String? , listener: CompressListener?) { viewModelScope.launch { CompressPictureUtil.compressImageByHuffman(path, quality, totalSize, desPath, listener) } } }Copy the code
private fun compressImage() {
vm.compressImage(
path = path,
quality = intArrayOf(100),
totalSize = 100,
desPath = desPath,
listener = object : CompressListener {
override fun startCompress() {
showLoading("Compressing")
}
override fun completedCompress() {
hideLoading()
Glide.with(this@MainActivity).load(File(desPath)).into(iv2)
}
})
}
Copy the code
Pay attention to
1, Support armeabi, ArmeabI-V7A, ARM64-V8A
2. The compression process is a time-consuming operation, using kotlin coroutine to switch threads
3, picture compression has a maximum limit, if you want to specify how many KB compression, please use other compression methods.
### Use effect
Compress 3.58m images losslessly to 100KB
- Code github.com/ewgcat/Comp…