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優勢:

減小前端圖片網絡請求次數,便於傳輸css

缺點:

不便於修改,影響代碼閱讀,轉成的base64字符串比原始圖片體積更大,因此大圖片轉成base64後反而請求更慢前端

總結:

在圖標之類不常修改,且圖片較小時使用base64能夠優化網頁速度網絡

相關文章
相關標籤/搜索