java base64相关
文件转Base64:
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; }
读取InputStream:
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(); }
前端css用法:
#test { background: url(data:image/gif;base64,R0lGODlhHAAmAKIHAKqqqsvLy0hISObm5vf394uLiwAAAP///yH5B…EoqQqJKAIBaQOVKHAXr3t7txgBjboSvB8EpLoFZywOAo3LFE5lYs/QW9LT1TRk1V7S2xYJADs=) no-repeat center; }
前端img标签:
<img src="data:image/gif;base64,R0lGODlhHAAmAKIHAKqqqsvLy0hISObm5vf394uLiwAAAP///yH5B…EoqQqJKAIBaQOVKHAXr3t7txgBjboSvB8EpLoFZywOAo3LFE5lYs/QW9LT1TRk1V7S2xYJADs=">
使用base64优点:
减少前端图片网络请求次数,便于传输
缺点:
不便于修改,影响代码阅读,转成的base64字符串比原始图片体积更大,所以大图片转成base64后反而请求更慢
总结:
在图标之类不常修改,且图片较小时使用base64可以优化网页速度