图片以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>
相关文章
相关标签/搜索