压缩分为两种,一种是像素压缩,一种是数据压缩。 这里我简单的写一下数据压缩的代码。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import java.io.*;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
/**
* Created by clear on 2017/9/13.
*/
public class GzipUtil {
public static byte[] gzip(byte[] data) throws Exception {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream);
gzipOutputStream.write(data);
gzipOutputStream.finish();
gzipOutputStream.close();
byte[] res = byteArrayOutputStream.toByteArray();
byteArrayOutputStream.close();
return res;
}
public static byte[] unzip(byte[] data) throws Exception {
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data);
GZIPInputStream gzipInputStream = new GZIPInputStream(byteArrayInputStream);
byte[] buf = new byte[1024];
int num = -1;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
while ((num = gzipInputStream.read(buf, 0, buf.length)) != -1) {
byteArrayOutputStream.write(buf, 0, num);
}
gzipInputStream.close();
byteArrayInputStream.close();
byte[] res = byteArrayOutputStream.toByteArray();
byteArrayOutputStream.flush();
byteArrayOutputStream.close();
return res;
}
public static void main(String[] args) throws Exception {
String filePath = System.getProperty("user.dir") + File.separator + "sources" + File.separator + "slamdunk.jpg";
FileInputStream fileInputStream = new FileInputStream(filePath);
byte[] buf = new byte[fileInputStream.available()];
System.out.println(buf.length);
fileInputStream.read(buf);
byte[] res = gzip(buf);
System.out.println(res.length);
byte[] res2 = unzip(res);
System.out.println(res2.length);
String targetFilePath = System.getProperty("user.dir") + File.separator + "receive" + File.separator + "slamdunk.jpg";
FileOutputStream targetOutputStream = new FileOutputStream(targetFilePath);
targetOutputStream.write(res2);
targetOutputStream.close();
}
}