第一种:
/*** 在线图片转换成base64字符串* @param imgURL 图片地址* @return*/public static String ImageToBase64ByOnline(String imgURL) {ByteArrayOutputStream data = new ByteArrayOutputStream();try {// 创建URLURL url = new URL(imgURL);byte[] by = new byte[1024];// 创建链接HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setRequestMethod("GET");conn.setConnectTimeout(5000);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();}// 对字节数组Base64编码BASE64Encoder encoder = new BASE64Encoder();return encoder.encode(data.toByteArray());}
第二种:
/*** 获取图片Base64流* File file*/public static String getStrImgBase64(URL url){// 对图像进行base64编码String strImgBase64 = "";try {InputStream is = url.openStream();byte[] imageBytes = IOUtils.toByteArray(is);strImgBase64 = new String(Base64.encodeBase64(imageBytes));} catch (IOException e) {e.printStackTrace();}return strImgBase64;}