圖片以base64方式展現

遇到一個需求,圖片須要在瀏覽器離線展現。html

剛開始沒想到什麼辦法,無心中發現kindeditor能夠直接截圖粘貼,沒有上傳就展現出來,查看html元素,發現圖片是已base64展現展示的。java

實現思路:在有網絡的時候,將圖片的base64數據緩存到瀏覽器端的localStorage;無網絡則能夠從localStorage讀取base64數據展現圖片,以base64方式展現圖片以下。spring

一、主要依賴庫數據庫

<dependency>
	<groupId>commons-codec</groupId>
	<artifactId>commons-codec</artifactId>
	<version>1.9</version>
</dependency>

二、對圖片的字節碼編碼成base64字符串apache

package com.wss.lsl.demo.base64.service.impl;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.wss.lsl.demo.base64.service.ImageService;

@Service("imageService")
public class ImageServiceImpl implements ImageService {
		
	private static final Logger LOG = LoggerFactory.getLogger(ImageServiceImpl.class);
	
	@Override
	public String image2Base64(String imageFile) {
		LOG.info("圖片轉化爲base64編碼參數:imageFile={}", imageFile);
		
		BufferedInputStream bis = null;
		String result = null;
		byte[] data = null;
		try {
			bis = new BufferedInputStream(new FileInputStream(new File(imageFile)));
			int count = bis.available();
			data = new byte[count];
			bis.read(data);
			result = Base64.encodeBase64String(data);
		} catch (Exception e) {
			// ingore
		} finally {
			try {
				bis.close();
			} catch (IOException e) {
				// ingore
			}
		}
		LOG.info("圖片轉化爲base64編碼結果:result={}", result);
		return result;
	}

}

三、controller獲取base64數據瀏覽器

@Controller
@RequestMapping("/base64")
public class Base64Controller {
	
	private static final Logger LOG = LoggerFactory.getLogger(Base64Controller.class);
	@Autowired
	private ImageService imageService;
	
	@RequestMapping(value="/show")
	public String show(Model model, String id){
		LOG.info("圖片以base64格式展現");
		
		try {
			String imageFile = getFilePathFromDb(id); //  從數據庫讀取圖片路徑
			String result = imageService.image2Base64(imageFile);
			model.addAttribute("result", result);
		} catch (Exception e) {
			LOG.error("圖片轉化爲base64格式發生異常", e);
		}
		
		return "base64/show";
	}
}

四、頁面展現圖片緩存

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>以base64格式展現圖片</title>
</head>
<body>
	<c:choose>
		<c:when test="${empty result }">
			圖片編碼失敗
		</c:when>
		<c:otherwise>
			<img alt="" src="data:image/png;base64,${result }" />
		</c:otherwise>
	</c:choose>
</body>
</html>
相關文章
相關標籤/搜索