package com.zcloud.util; import org.apache.commons.codec.binary.Base64; import java.io.*; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; /** * 说明:BASE64处理 * 作者:luoxiaobao * 官网:www.qdkjchina.com */ public class ImageAnd64Binary { public static void main(String[] args) { String imgSrcPath = "H:/1.jpg"; // 生成64编码的图片的路径 String imgCreatePath = "H:/123.png"; // 将64编码生成图片的路径 imgCreatePath = imgCreatePath.replaceAll("\\\\", "/"); System.out.println(imgCreatePath); String strImg = getImageStr(imgSrcPath); System.out.println(strImg); generateImage(strImg, imgCreatePath); } /** * 将图片文件转化为字节数组字符串,并对其进行Base64编码处理 * * @param imgSrcPath * 生成64编码的图片的路径 * @return */ public static String getImageStr(String imgSrcPath) { InputStream in = null; byte[] data = null; // 读取图片字节数组 try { in = new FileInputStream(imgSrcPath); data = new byte[in.available()]; in.read(data); in.close(); } catch (IOException e) { e.printStackTrace(); } // 对字节数组Base64编码 return Base64.encodeBase64String(data);// 返回Base64编码过的字节数组字符串 } /** * 对字节数组字符串进行Base64解码并生成图片 * * @param imgStr * 转换为图片的字符串 * @param imgCreatePath * 将64编码生成图片的路径 * @return */ public static boolean generateImage(String imgStr, String imgCreatePath) { if (imgStr == null) // 图像数据为空 return false; try { // Base64解码 byte[] b = Base64.decodeBase64(imgStr); for (int i = 0; i < b.length; ++i) { if (b[i] < 0) {// 调整异常数据 b[i] += 256; } } OutputStream out = new FileOutputStream(imgCreatePath); out.write(b); out.flush(); out.close(); return true; } catch (Exception e) { return false; } } /** * 字符串的压缩 * * @param base64 待压缩的字符串 * * @return 返回压缩后的字符串 * * @throws IOException */ public static String zipBase64(String base64) throws IOException { if (null == base64 || base64.length() <= 0) { return base64; } // 创建一个新的 byte 数组输出流 ByteArrayOutputStream out = new ByteArrayOutputStream(); // 使用默认缓冲区大小创建新的输出流 GZIPOutputStream gzip = new GZIPOutputStream( out ); // 将 b.length 个字节写入此输出流 gzip.write( base64.getBytes() ); gzip.close(); // 使用指定的 charsetName,通过解码字节将缓冲区内容转换为字符串 return out.toString( "ISO-8859-1" ); } /** * 字符串的解压 * * @param zipBase64 需要解压的字符串 * * @return 返回解压缩后的字符串 * * @throws IOException */ public static String upZip(String zipBase64) throws IOException { if (null == zipBase64 || zipBase64.length() <= 0) { return zipBase64; } // 创建一个新的 byte 数组输出流 ByteArrayOutputStream out = new ByteArrayOutputStream(); // 创建一个 ByteArrayInputStream,使用 buf 作为其缓冲区数组 ByteArrayInputStream in = new ByteArrayInputStream( zipBase64.getBytes( "ISO-8859-1" ) ); // 使用默认缓冲区大小创建新的输入流 GZIPInputStream gzip = new GZIPInputStream( in ); byte[] buffer = new byte[256]; int n = 0; while ((n = gzip.read( buffer )) >= 0) {// 将未压缩数据读入字节数组 // 将指定 byte 数组中从偏移量 off 开始的 len 个字节写入此 byte数组输出流 out.write( buffer, 0, n ); } // 使用指定的 charsetName,通过解码字节将缓冲区内容转换为字符串 return out.toString( "ISO-8859-1" ); } }