package com.doumee.core.utils; import org.apache.commons.codec.binary.Base64; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; import java.io.*; import java.net.HttpURLConnection; import java.net.URL; public class ImageBase64Util { /** * 将图片转换成Base64编码 * @param imgFile 待处理图片 * @return */ public static String getImgStr(String imgFile) { // 将图片文件转化为字节数组字符串,并对其进行Base64编码处理 InputStream in = null; byte[] data = null; // 读取图片字节数组 try { in = new FileInputStream(imgFile); data = new byte[in.available()]; in.read(data); in.close(); } catch (IOException e) { e.printStackTrace(); } return Base64.encodeBase64String(data); } /** * 对字节数组字符串进行Base64解码并生成图片 * @param imgStr 图片数据 * @param imgFilePath 保存图片全路径地址 * @return */ public static boolean generateImage(String imgStr, String imgFilePath) { // if (imgStr == null) // 图像数据为空 return false; BASE64Decoder decoder = new BASE64Decoder(); try { // Base64解码 byte[] b = decoder.decodeBuffer(imgStr); for (int i = 0; i < b.length; ++i) { if (b[i] < 0) {// 调整异常数据 b[i] += 256; } } // 生成jpg图片 OutputStream out = new FileOutputStream(imgFilePath); out.write(b); out.flush(); out.close(); return true; } catch (Exception e) { return false; } } /** * 远程读取image转换为Base64字符串 * @param imgUrl * @return */ public static String Image2Base64(String imgUrl) { URL url = null; InputStream is = null; ByteArrayOutputStream outStream = null; HttpURLConnection httpUrl = null; try{ url = new URL(imgUrl); httpUrl = (HttpURLConnection) url.openConnection(); httpUrl.connect(); httpUrl.getInputStream(); is = httpUrl.getInputStream(); outStream = new ByteArrayOutputStream(); //创建一个Buffer字符串 byte[] buffer = new byte[1024]; //每次读取的字符串长度,如果为-1,代表全部读取完毕 int len = 0; //使用一个输入流从buffer里把数据读取出来 while( (len=is.read(buffer)) != -1 ){ //用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度 outStream.write(buffer, 0, len); } // 对字节数组Base64编码 return Base64.encodeBase64String(outStream.toByteArray()); // return new BASE64Encoder().encode(outStream.toByteArray()); }catch (Exception e) { e.printStackTrace(); } finally{ if(is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } if(outStream != null) { try { outStream.close(); } catch (IOException e) { e.printStackTrace(); } } if(httpUrl != null) { httpUrl.disconnect(); } } return null; } public static void main(String[] args) { String url= "http://175.27.187.84/file4/member/20223402/DM1005.png";// 待处理的图片 String imgbese = Image2Base64(url); System.out.println(imgbese.replace("\r\n", "")); // String url= "D:\\1.jpg";// 新生成的图片 // generateImage(imgbese, url); } }