图片以base64方式展示

遇到一个需求,图片需要在浏览器离线展示。

刚开始没想到什么办法,无意中发现kindeditor可以直接截图粘贴,没有上传就展示出来,查看html元素,发现图片是已base64展示展现的。

实现思路:在有网络的时候,将图片的base64数据缓存到浏览器端的localStorage;无网络则可以从localStorage读取base64数据展示图片,以base64方式展示图片如下。

1、主要依赖库

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

2、对图片的字节码编码成base64字符串

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;
	}

}

3、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";
	}
}

4、页面展示图片

<%@ 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="https://img-blog.csdnimg.cn/2022010615524825402.png" />
		</c:otherwise>
	</c:choose>
</body>
</html>

 

转载于:https://my.oschina.net/u/2007041/blog/707465

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值