为了直观加了base64
PHP 代码:
<?php
$a = gzcompress("abc");
echo base64_encode($a);
//输出: eJxLTEoGAAJNASc=
解码:gzuncompress();
源码提示默认使用的是 zlib的 deflate 进行编码的;
function gzcompress ($data, $level = -1, $encoding = ZLIB_ENCODING_DEFLATE) {}
对应的 JAVA处理代码 (JDK1.8):
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Base64;
import java.util.zip.Deflater;
import java.util.zip.Inflater;
public class GzCompress{
public static void main(String[] args) {
String encodeCompressd = "eJxLTEoGAAJNASc=";
byte[] compressd = Base64.getDecoder().decode( encodeCompressd );
String origin = new String( decompress(compressd) );
System.out.println("origin: "+origin);
byte[] _compressd = compress(origin.getBytes());
byte[] _encodeCompress = Base64.getEncoder().encode(_compressd);
System.out.println(new String(_encodeCompress));
}
public static byte[] decompress(byte[] data) {
byte[] output = new byte[0];
Inflater decompresser = new Inflater();
decompresser.reset();
decompresser.setInput(data);
ByteArrayOutputStream o = new ByteArrayOutputStream(data.length);
try {
byte[] buf = new byte[1024];
while (!decompresser.finished()) {
int i = decompresser.inflate(buf);
o.write(buf, 0, i);
}
output = o.toByteArray();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
o.close();
} catch (IOException e) {
e.printStackTrace();
}
}
decompresser.end();
return output;
}
public static byte[] compress( byte[] bytes ){
byte[] output = new byte[1024];
Deflater compresser = new Deflater();
compresser.setInput(bytes);
compresser.finish();
int compressedDataLength = compresser.deflate(output);
return Arrays.copyOf(output,compressedDataLength);
}
}
对应输出:
origin: abc
compressLength:11
eJxLTEoGAAJNASc=