图片base64报文压缩
1.使用GZIP压缩Base64字符串
public static String compressBase64(String base64Input) throws IOException {
// 解码Base64字符串为字节数组
byte[] data = java.util.Base64.getDecoder().decode(base64Input);
// 使用GZIP压缩字节数组
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try (GZIPOutputStream gzip = new GZIPOutputStream(bos)) {
gzip.write(data);
}
byte[] compressedData = bos.toByteArray();
// 将压缩后的字节数组编码为Base64字符串
return java.util.Base64.getEncoder().encodeToString(compressedData);
}
2.解压压缩后的Base64字符串
public static String decompressBase64(String compressedBase64) throws IOException {
// 解码Base64字符串为压缩后的字节数组
byte[] compressedData = java.util.Base64.getDecoder().decode(compressedBase64);
// 解压字节数组
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try (GZIPInputStream gzip = new GZIPInputStream(new java.io.ByteArrayInputStream(compressedData))) {
byte[] buffer = new byte[1024];
int len;
while ((len = gzip.read(buffer)) > 0) {
bos.write(buffer, 0, len);
}
}
byte[] decompressedData = bos.toByteArray();
// 将解压后的字节数组重新编码为Base64字符串
return java.util.Base64.getEncoder().encodeToString(decompressedData);
}
3.计算报文大小
/**
* 获取报文字节数
*
* @param str 字符串
* @return 返回字节数
*/
public static double calculateStringBytesSize(String str) {
// 计算字符串的字节数
int byteCount = str.getBytes(StandardCharsets.UTF_8).length;
return byteCount;
}
/**
* 将字节数转换为KB并四舍五入保留一位小数
*
* @param bytes 字节数
* @return 转换后的KB值
*/
public static BigDecimal toKBWithDecimal(double bytes) {
//return round(bytes / BYTE_IN_KB, 2);
//将字节数转换为KB并向上取整
//return (long) Math.ceil(bytes / BYTE_IN_KB);
BigDecimal bd = new BigDecimal(bytes);
BigDecimal divide = bd.divide(new BigDecimal(BYTE_IN_KB), 1, RoundingMode.HALF_UP);
return divide;
}
4.验证
public static void main(String[] args) {
String body="/9j/4AAQSkZJRgABAQAA........";
String compressed = compressBase64(body);
System.out.println("compressed 压缩后的字符串长度:" + compressed.length());
System.out.println("compressed:kb:" + toKBWithDecimal(calculateStringBytesSize(compressed)));
String decompressed = decompressBase64(compressed);
System.out.println("decompressed解压缩后的字符串长度:" + decompressed.length());
System.out.println("compressed:kb:" + toKBWithDecimal(calculateStringBytesSize(decompressed)));
System.out.println("decompressed base64验证结果: " + body.equals(decompressed));
}

浙公网安备 33010602011771号