【Demo】Base64编码图片转json的效果对比
1 public class Test { 2 public static void main(String[] args) throws IOException { 3 byte[] data = Test.getFileByte(); 4 System.out.println("压缩前的大小:" + data.length / 1024.0 + " KB"); 5 //压缩 6 byte[] resByte = Test.gzipFile(data); 7 System.out.println("压缩以后的大小:" + resByte.length / 1024.0 + " KB"); 8 9 //base64 10 String encode = Base64.getEncoder().encodeToString(resByte); 11 System.out.println("base64以后的大小:" + encode.length() / 1024.0 + " KB"); 12 13 String json1 = GsonUtils.toJson(data); 14 System.out.println("原始数据转json大小:" + json1.length() / 1024.0 + " KB"); 15 String json2 = GsonUtils.toJson(resByte); 16 System.out.println("压缩后转json大小:" + json2.length() / 1024.0 + " KB"); 17 String json3 = GsonUtils.toJson(encode); 18 System.out.println("压缩并base64以后转json大小:" + json3.length() / 1024.0 19 + " KB"); 20 System.out.println((double) json1.length() / data.length + " 倍"); 21 System.out.println((double) json2.length() / data.length + " 倍"); 22 System.out.println((double) json3.length() / data.length + " 倍"); 23 24 } 25 26 private static byte[] gzipFile(byte[] data) throws IOException { 27 ByteArrayOutputStream bos1 = new ByteArrayOutputStream(); 28 29 GZIPOutputStream gzip = new GZIPOutputStream(bos1); 30 gzip.write(data); 31 32 gzip.flush(); 33 gzip.close(); 34 gzip.finish(); 35 36 return bos1.toByteArray(); 37 } 38 39 private static byte[] getFileByte() throws IOException { 40 String path = "D:\\111.png"; 41 File file = new File(path); 42 InputStream fis = null; 43 ByteArrayOutputStream bos = null; 44 byte[] data = new byte[0]; 45 try { 46 fis = new FileInputStream(file); 47 48 bos = new ByteArrayOutputStream((int) file.length()); 49 50 byte[] buf = new byte[1024]; 51 int len = -1; 52 while ((len = fis.read(buf)) != -1) { 53 bos.write(buf, 0, len); 54 } 55 data = bos.toByteArray(); 56 } catch (Exception e) { 57 e.printStackTrace(); 58 } finally { 59 if (bos != null) { 60 bos.close(); 61 } 62 63 if (fis != null) { 64 fis.close(); 65 } 66 } 67 return data; 68 } 69 }
结果:
压缩前的大小:1.9638671875 KB 压缩以后的大小:1.97265625 KB base64以后的大小:2.6328125 KB 原始数据转json大小:7.1806640625 KB 压缩后转json大小:7.263671875 KB 压缩并base64以后转json大小:2.64453125 KB 3.6563898557931376 倍 3.6986573843858777 倍 1.3465937344604675 倍