Android 字串壓縮 (String Compress)

最近在做專題的時候,

需要把JSON字串轉成QRCODE,

可是直接轉換的話,QRCODE會變得非常複雜,難以辨識,

因此上網找了一下,果然有人使用GZIP來壓縮字串,

可是在我使用了以後,

QRCODE卻無法正確被解析,

查了一下發現應該是一些Header遺失了,

導致GZIP無法正確解壓縮,

因此我決定壓縮以後再把字串用Base64編碼一次,

解壓縮的時候先用Base64解碼,

藉此把Header保留,

一試果然成功了,

不過此方法會導致壓縮率減小,

但是也夠用了

以下是程式碼,獻醜了!

ZipUtil
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
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import android.util.Base64;

public class ZipUtil {
// 壓縮
public static String compress(String str) throws IOException {
if (str == null || str.length() == 0) {
return str;
}

ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(out);
gzip.write(str.getBytes());
gzip.close();

String encode = Base64.encodeToString(out.toString("ISO-8859-1")
.getBytes("ISO-8859-1"), Base64.DEFAULT);

return encode;
}

// 解壓縮
public static String uncompress(String str) throws IOException {
if (str == null || str.length() == 0) {
return str;
}
byte[] src = Base64.decode(str.getBytes("ISO-8859-1"), Base64.DEFAULT);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ByteArrayInputStream in = new ByteArrayInputStream(src);
GZIPInputStream gunzip = new GZIPInputStream(in);
byte[] buffer = new byte[256];
int n;
while ((n = gunzip.read(buffer)) >= 0) {
out.write(buffer, 0, n);
}

return out.toString();
}
}

大部分的程式碼都是參考這裡

附上壓縮前跟壓縮後的QRCODE差異

Before
Before

After
After