package com.ld.igds.util; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; import java.io.*; /** * */ @SuppressWarnings("restriction") public class Base64Util { public static String UTF_8 = "UTF-8"; public static String BASE_IMG_START = "data:image/jpg;base64,"; /** * 根据地址,把图片转换为Base64字符串 *
* data:image/jpg;base64, * * @param diskFile * @return */ public static String getImageStr(String diskFile) { InputStream in = null; byte[] data = null; // 读取图片字节数组 try { in = new FileInputStream(diskFile); data = new byte[in.available()]; in.read(data); // in.close(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (null != in) in.close(); } catch (Exception e) { } } BASE64Encoder encoder = new BASE64Encoder(); return BASE_IMG_START + encoder.encode(data); } /** * 对字节数组字符串进行Base64解码并生成图片 * * @param imgStr * @return */ public static boolean generateImage(String imgStr, String diskFile) { if (imgStr == null) return false; if (imgStr.startsWith("data:")) { imgStr = imgStr.substring(BASE_IMG_START.length()); } BASE64Decoder decoder = new BASE64Decoder(); OutputStream out = null; try { // Base64解码 byte[] b = decoder.decodeBuffer(imgStr); for (int i = 0; i < b.length; ++i) { if (b[i] < 0) { b[i] += 256; } } // 生成jpeg图片 out = new FileOutputStream(diskFile); out.write(b); out.flush(); // out.close(); return true; } catch (Exception e) { return false; } finally { try { if (null != out) out.close(); } catch (Exception e) { } } } public static String encode2String(byte[] data) { BASE64Encoder encoder = new BASE64Encoder(); return BASE_IMG_START + encoder.encode(data); } // public static void main(String[] args) { // String disFile = // "D:\\IGDS\\INOUT\\202108\\intou_in_202108241321178261.jpg"; // // // String strImg = getImageStr(disFile); // // System.out.println(strImg); // // String disFile2 = "D:\\IGDS\\INOUT\\202108\\" + // System.currentTimeMillis() + "_new.jpg"; // // generateImage(strImg, disFile2); // } }