使用libjpeg进行图片压缩(哈夫曼算法,无损压缩)

893 阅读1分钟

Huffman算法

  • Huffman算法也是一种无损压缩算法,但与LZW压缩算法不同,Huffman需要得到每种字符出现概率的先验知识。通过计算字符序列中每种字符出现的频率,为每种字符进行唯一的编码设计,使得频率高的字符占的位数短,而频率低的字符长,来达到压缩的目的。通常可以节省20%~90%的空间,很大程度上依赖数据的特性!Huffman编码是变长编码,即每种字符对应的编码长度不唯一。

  • 前缀码:任何一个字符的编码都不是同一字符集中另一种字符编码的前缀。Huffman编码为最优前缀码,即压缩后数据量最小。

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' }
    		}
    	}
	

Step 2. Add the dependency


	dependencies {
	        implementation 'com.github.ewgcat:CompressImageByHuffman:1.0.6'
	}
	

class BaseViewModel : ViewModel() {
    /**
     * 没法在主线程完成的繁重操作
     */
    fun compressImage( path: String?,
                        quality: IntArray,
                        totalSize: Int,
                        desPath: String?,
                        listener: CompressListener?) {
        viewModelScope.launch {
            CompressPictureUtil.compressImageByHuffman(path, quality, totalSize, desPath, listener)
        }
    }
}


    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)
                }
            })
    }
    

注意

1、支持armeabi,armeabi-v7a,arm64-v8a

2、压缩过程是耗时操作,使用kotlin协程切换线程

3、图片压缩有最大极限,如果要指定压缩到多少KB,请结合其他压缩方式使用。

###使用效果

将3.58M的图片无损压缩到100KB

本方案是为了解决保利物业员工巡视拍照上传图片而解决服务器端减少存储