注意需要过滤:\r \n数据
jkd1.7的
import sun.misc.BASE64Decoder;import sun.misc.BASE64Encoder;
/** * 网络图片转换Base64的方法 * * @param netImagePath */ public static String NetImageToBase64(String netImagePath) { final ByteArrayOutputStream data = new ByteArrayOutputStream(); String strNetImageToBase64 = null; try { // 创建URL URL url = new URL(netImagePath); final byte[] by = new byte[1024]; // 创建链接 final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5000); if(conn.getResponseCode() != HttpURLConnection.HTTP_OK) { return strNetImageToBase64; //连接失败/链接失效/图片不存在 } Thread thread =new Thread(new Runnable() { @Override public void run() { try { InputStream is = conn.getInputStream(); // 将内容读取内存中 int len = -1; while ((len = is.read(by)) != -1) { data.write(by, 0, len); } // 关闭流 is.close(); } catch (IOException e) { e.printStackTrace(); } } }); thread.start(); try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } // 对字节数组Base64编码 BASE64Encoder encoder = new BASE64Encoder(); strNetImageToBase64 = encoder.encode(data.toByteArray()); // 删除 \r\n strNetImageToBase64 = strNetImageToBase64.replaceAll("\n", "").replaceAll("\r", ""); strNetImageToBase64 = "data:image/jpeg;base64," + strNetImageToBase64; } catch (IOException e) { e.printStackTrace(); } return strNetImageToBase64; }
1.8java.util.Base64包
/** * 转换为base64格式 * * @param image * @return */ public static String encode2Base64Jpg(BufferedImage image) { ByteArrayOutputStream baos = new ByteArrayOutputStream();// io流 try { ImageIO.write(image, "jpg", baos); } catch (IOException e) { e.printStackTrace(); } byte[] bytes = baos.toByteArray();// 转换成字节 Base64.Encoder encoder = Base64.getEncoder(); String jpgBase64 = encoder.encodeToString(bytes).trim();// 转换成base64串 jpgBase64 = jpgBase64.replaceAll("\n", "").replaceAll("\r", "");// 删除 \r\n return "data:image/jpeg;base64," + jpgBase64; }
其他本地图片处理
/** * 图片转化成base64字符串 * @param imgPath * @return */ public static String GetImageStr(String imgPath) {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理 String imgFile = imgPath;// 待处理的图片 InputStream in = null; byte[] data = null; String encode = null; // 返回Base64编码过的字节数组字符串 // 对字节数组Base64编码 BASE64Encoder encoder = new BASE64Encoder(); try { // 读取图片字节数组 in = new FileInputStream(imgFile); data = new byte[in.available()]; in.read(data); encode = encoder.encode(data); } catch (IOException e) { e.printStackTrace(); } finally { try { in.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return encode; }
原文地址:https://www.cnblogs.com/achengmu/p/11813995.html
时间: 2024-11-03 17:50:40