哈夫曼编码实现压缩与解压
- 一、基本概念
- 二、思路分析
- 三、代码实现
一、基本概念
哈夫曼编码(Huffman Coding),又称霍夫曼编码,是一种编码方式,哈夫曼编码是可变字长编码(VLC)的一种。Huffman于1952年提出一种编码方法,该方法完全依据字符出现概率来构造异字头的平均长度最短的码字,有时称之为最佳编码,一般就叫做Huffman编码(有时也称为霍夫曼编码)。
赫夫曼码的码字(各符号的代码)是异前置码字,即任一码字不会是另一码字的前面部分,这使各码字可以连在一起传送,中间不需另加隔离符号,只要传送时不出错,收端仍可分离各个码字,不致混淆。
二、思路分析
哈夫曼编码就是利用哈夫曼树来实现的,通过构造哈夫曼树,一半在构造过程中,向左路径规定为0,向右路径规定为1,这样元素路径上的0和1就构成了哈夫曼编码。下面看一个例子,我们以在哈夫曼树中提到的序列为例:13,7,8,3,29,6,1,构造哈夫曼树如下:
如上图,我们可以看到已经给左右分支都编上了0/1,这样29的编码就是1,7的编码就是100,8的编码就是101,1的编码就是11000,剩下的以此类推。
利用哈夫曼编码的特征,我们可以使用哈夫曼编码进行压缩文件,以一个简单的字符串为例:“i like like like java do you like a java”,如果直接使用二进制进行编码,则编码长度为359,下面我们来看使用哈夫曼编码的情况。我们首先统计各个字符出现的次数来作为权值,构造一棵哈夫曼树,其中:d:1 y:1 u:1 j:1 v:2 o:2 l:2 k:4 e:4 i:5 a:5 空格:9。
然后使用上述方法进行编码:
o:1000 u:10010 d:100110 y:100111 i:101 a:110 k:1110 e:1111 j:0000 v:0001 l:001 空格:01
所以整个字符串的编码就是:1010100110111101111010011011110111101001101111011110100001100001110011001101000011001111000100100100110111101111011100100001100001110
长度:133,压缩率(359-133)/359=62.9%。
注意:在构造哈夫曼树时,由于哈夫曼树的结构可能不同,所以编码也可能不同,但是wpl是一样的,都是最小的。最后生成的哈夫曼编码长度也是一样的。
三、代码实现
利用哈夫曼编码进行压缩分为以下几步:
- 将待压缩文件存入byte[]数组中
- 将byte[]数组中的内容进行统计,并返回节点所组成的list
- 创建哈夫曼树
- 利用哈夫曼树进行哈夫曼编码并存放起来
- 根据哈夫曼编码得到的编码表,将进行哈夫曼编码后的0/1形式的串按8位划分并转化为十进制形式进行存储
解压操作是压缩操作的逆操作:
- 首先接收压缩后的以十进制存放的byte[]数组以及编码表
- 将编码后的十进制数还原为二进制数,即0/1形式
- 根据编码表,将二进制形式串还原为初始形式。
package com.huffmancode;
import java.io.*;
import java.util.*;
/**
* @author dankejun
* @create 2020/9/915:30
*/
public class HuffmanCode {
public static void main(String[] args) {
String content = "i like like like java do you like a java";
byte[] contentBytes = content.getBytes();
System.out.println("原数组长度: " + contentBytes.length);//40
//
byte[] huffmanCodeBytes = huffmanZip(contentBytes);
System.out.println("huffmanCodeBytes" + Arrays.toString(huffmanCodeBytes));
//
byte[] bytes = decode(huffmanCodes, huffmanCodeBytes);
System.out.println(new String(bytes));
}
//数据的解压
private static byte[] decode(Map<Byte, String> huffmanCodes, byte[] huffmanBytes) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < huffmanBytes.length; i++) {
byte b = huffmanBytes[i];
boolean flag = (i == huffmanBytes.length - 1);
stringBuilder.append(byteToBitString(!flag, b));
}
System.out.print(stringBuilder);
System.out.println();
Map<String, Byte> map = new HashMap<>();
for (Map.Entry<Byte, String> entry : huffmanCodes.entrySet()) {
map.put(entry.getValue(), entry.getKey());
}
List<Byte> list = new ArrayList<>();
for (int i = 0; i < stringBuilder.length();) {
int count = 1;
boolean flag = true;
Byte b = null;
while (flag) {
String key = stringBuilder.substring(i, i + count);
b = map.get(key);
if (b == null) {
count++;
} else {
flag = false;
}
}
list.add(b);
i += count;
}
byte[] b = new byte[list.size()];
for (int i = 0; i < b.length; i++) {
b[i] = list.get(i);
}
return b;
}
//把压缩的byte数组中的十进制数转化为2进制数
private static String byteToBitString(boolean flag, byte b) {
int temp = b;
if (flag) {
temp |= 256;
}
String str = Integer.toBinaryString(temp);
if (flag) {
return str.substring(str.length() - 8);
} else {
return str;
}
}
//封装压缩操作
private static byte[] huffmanZip(byte[] bytes) {
List<Node> nodes = getNodes(bytes);
Node root = creatHuffmanTree(nodes);
Map<Byte, String> huffmanCodes = getCodes(root);
byte[] huffmanCodeBytes = zip(bytes, huffmanCodes);
return huffmanCodeBytes;
}
/**
*
* @param bytes 原始的字符串对应的数组
* @param huffmanCodes 生成的哈夫曼树编码map
* @return 返回哈夫曼编码处理后的byte[]
*/
private static byte[] zip(byte[] bytes , Map<Byte,String> huffmanCodes) {
StringBuilder builder = new StringBuilder();
for (byte b : bytes) {
builder.append(huffmanCodes.get(b));
}
int len;
if (builder.length() % 8 == 0) {
len = builder.length() / 8;
} else {
len = builder.length() / 8 + 1;
}
byte[] huffmanCodeBytes = new byte[len];
int index = 0;
for (int i = 0; i < builder.length(); i = i + 8) {
String strByte;
if (i + 8 > builder.length()) {
strByte = builder.substring(i);
} else {
strByte = builder.substring(i, i + 8);
}
huffmanCodeBytes[index] = (byte) Integer.parseInt(strByte,2);
index++;
}
return huffmanCodeBytes;
}
static Map<Byte, String> huffmanCodes = new HashMap<>();
static StringBuilder stringBuilder = new StringBuilder();
private static Map<Byte, String> getCodes(Node root) {
if (root == null) {
return null;
}
getCodes(root.left, "0", stringBuilder);
getCodes(root.right, "1", stringBuilder);
return huffmanCodes;
}
/**
* 将传入的node节点的所有叶子节点哈夫曼编码得到,并放入到huffmanCode集合中
* @param node 传入节点
* @param code 路径,左0右1
* @param stringBuilder 用于拼接路径
*/
private static void getCodes(Node node, String code, StringBuilder stringBuilder) {
StringBuilder builder = new StringBuilder(stringBuilder);
builder.append(code);
if (node != null) {
if (node.data == null) {
getCodes(node.left, "0", builder);
getCodes(node.right, "1", builder);
} else {
huffmanCodes.put(node.data, builder.toString());
}
}
}
/**
*
* @param bytes 接收字节数组
* @return 返回的就算List
*/
private static List<Node> getNodes(byte[] bytes) {
List<Node> nodes = new ArrayList<>();
Map<Byte, Integer> counts = new HashMap<>();
for (Byte b : bytes) {
Integer count = counts.get(b);
if (count == null) {
counts.put(b, 1);
} else {
counts.put(b, count+1);
}
}
for (Map.Entry<Byte, Integer> entry : counts.entrySet()) {
nodes.add(new Node(entry.getKey(), entry.getValue()));
}
return nodes;
}
//通过List创建哈夫曼树
private static Node creatHuffmanTree(List<Node> nodes) {
while (nodes.size() > 1) {
Collections.sort(nodes);
Node leftNode = nodes.get(0);
Node rightNode = nodes.get(1);
Node parent = new Node(null,leftNode.weight+rightNode.weight);
parent.left = leftNode;
parent.right = rightNode;
nodes.remove(leftNode);
nodes.remove(rightNode);
nodes.add(parent);
}
return nodes.get(0);
}
}
//创建节点
class Node implements Comparable<Node>{
Byte data;
int weight;
Node left;
Node right;
public Node(Byte data, int weight) {
this.data = data;
this.weight = weight;
}
@Override
public int compareTo(Node o) {
return this.weight-o.weight;
}
@Override
public String toString() {
return "Node{" +
"data=" + data +
", weight=" + weight +
'}';
}
}
测试结果:
除了对简单的字符串进行压缩解压外,我们可以加入流,来对文件进行压缩与解压操,对文件的压缩与解压操作的核心依然是以上内容,只是需要加入流来对文件进行读写。话不多说,直接上代码。
//压缩文件方法
/**
*
* @param srcFile 待压缩文件的全路径
* @param dstFile 文件压缩后存放路径
*/
public static void zipFile(String srcFile, String dstFile) {
//创建文件输出流
OutputStream os = null;
//创建文件输入流
InputStream is = null;
//创建对象输出流
ObjectOutputStream oos = null;
try {
is = new FileInputStream(srcFile);
//创建一个和源文件大小一样的byte[]
byte[] b = new byte[is.available()];
//读取文件
is.read(b);
//对文件压缩
byte[] huffmanBytes = huffmanZip(b);
//创建文件输出流存放压缩文件
os = new FileOutputStream(dstFile);
//创建一个和文件输出流关联的ObjectOutputStream
oos = new ObjectOutputStream(os);
//把哈夫曼编码过后的字节数组写入压缩文件
oos.writeObject(huffmanBytes);
//以对象流的方式写入哈夫曼编码,方便以后恢复原文件
oos.writeObject(huffmanCodes);
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (oos != null) {
oos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 解压文件
* @param zipFile 待解压文件全路径
* @param dstFile 解压后存放位置
*/
public static void unZip(String zipFile, String dstFile) {
//定义输入流
InputStream is = null;
//定义对象输入流
ObjectInputStream ois = null;
//定义输出流
OutputStream os = null;
try {
//创建文件输入流
is = new FileInputStream(zipFile);
//创建与输入流关联的对象输入流
ois = new ObjectInputStream(is);
//读取byte数组huffmanBytes
byte[] huffmanBytes = (byte[]) ois.readObject();
//读取哈夫曼编码表
Map<Byte, String> huffmanCodes = (Map<Byte, String>) ois.readObject();
//解码
byte[] bytes = decode(huffmanCodes, huffmanBytes);
//创建文件输出流
os = new FileOutputStream(dstFile);
//写文件到dstFile
os.write(bytes);
} catch (Exception e) {
System.out.println(e.getMessage());
}finally {
try {
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (ois != null) {
ois.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
测试一下
public static void main(String[] args) {
// 测试压缩文件
String srcFile = "d://src.bmp";
String dstFile = "d://dstFile.zip";
zipFile(srcFile, dstFile);
System.out.println("压缩文件ok");
}
测试结果:
这里如果我们使用电脑里的解压工具进行解压会发现该文件无法进行解压,那是因为文件压缩是我们自定义的,解压工具使用它的解码方式进行解压自然行不通,所以还需要再来使用我们自己的解码方式进行解压。
public static void main(String[] args) {
// 测试解压文件
String zipFile = "d://dstFile.zip";
String dstFile = "d://src2.bmp";
unZip(zipFile, dstFile);
System.out.println("解压成功~~");
}
测试结果: