public static String imgToBase64(InputStream inStream) { byte[] data = null; try { //available()获取长度 data = new byte[inStream.available()]; System.out.println(inStream.available()); inStream.read(data); inStream.close(); } catch (IOException e) { e.printStackTrace(); } BASE64Encoder encoder = new BASE64Encoder(); //"\\s"去除空白符 return encoder.encode(data).replaceAll("\\s*", ""); }
public static String getImgBase64(List<Marker> markers) { // 获取url String imgUrl = getBaiduUrlParameters(markers); System.out.println(imgUrl); // 发送请求 InputStream is = null; URL url = null; try { url = new URL(imgUrl); HttpURLConnection conn = null; conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(3000); conn.setRequestMethod("GET"); if (conn.getResponseCode() == 200) { is = conn.getInputStream(); String contentType = conn.getHeaderField("Content-Type");
//判断返回值类型 if (contentType.contains("image")) {
//这里的直接获取的InputStream须要进一步处理 return imgToBase64(new ByteArrayInputStream(readStream(is))); } } is.close(); } catch (IOException e) { e.printStackTrace(); } return null; }
public static byte[] readStream(InputStream inStream) throws IOException { ByteArrayOutputStream outSteam = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = -1; while ((len = inStream.read(buffer)) != -1) { outSteam.write(buffer, 0, len); } outSteam.close(); inStream.close(); return outSteam.toByteArray(); }
#test { background: url(data:image/gif;base64,R0lGODlhHAAmAKIHAKqqqsvLy0hISObm5vf394uLiwAAAP///yH5B…EoqQqJKAIBaQOVKHAXr3t7txgBjboSvB8EpLoFZywOAo3LFE5lYs/QW9LT1TRk1V7S2xYJADs=) no-repeat center; }
<img src="data:image/gif;base64,R0lGODlhHAAmAKIHAKqqqsvLy0hISObm5vf394uLiwAAAP///yH5B…EoqQqJKAIBaQOVKHAXr3t7txgBjboSvB8EpLoFZywOAo3LFE5lYs/QW9LT1TRk1V7S2xYJADs=">
减小前端图片网络请求次数,便于传输css
不便于修改,影响代码阅读,转成的base64字符串比原始图片体积更大,因此大图片转成base64后反而请求更慢前端
在图标之类不常修改,且图片较小时使用base64能够优化网页速度网络