使用base64
编码传输图片文件,在实际开发中也比较常见。在整个网站如果图片足够小复用性很高并且基本不会被更新(例如网站的logo)我们就可以考虑将图片转为base64
编码。使用css
的background
属性或img
标签的src
属性进行图片的展示,例如:
body {
background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA5QA…tgxSgaWqrow7zFIF+mvgHLlro7ghXwnsAAAAASUVORK5CYII=);
}
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA5QA…tgxSgaWqrow7zFIF+mvgHLlro7ghXwnsAAAAASUVORK5CYII=" alt="" id="img">
浏览器下载HTML
的同时加载base64
编码,就没有必要在向服务器单独请求图片资源(消耗一个http),这也是前端的一种简单优化。那么这样一种传输方式,如何实现转换与下载呢?
Java
实现图片base64
的转换
@Override
public String getBase64Str() {
// 读取 resources/static/lzh测试.png
URL url = this.getClass().getClassLoader().getResource("static/lzh测试.png");
if (url == null) {
log.error("图片资源不存在");
return null;
}
File file = null;
InputStream inputStream = null;
String base64Str = null;
try {
file = new File(url.toURI());
inputStream = new FileInputStream(file);
byte[] bytes = new byte[inputStream.available()];
inputStream.read(bytes);
// 将字节流数组转换为字符串
base64Str = Base64Utils.encodeToString(bytes);
// 获取图片后缀
String extension = getExtensionName(file.getName());
base64Str = "data:image/" + extension + ";base64," + base64Str;
} catch (Exception e) {
log.error(e);
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
log.error(e);
}
}
}
return base64Str;
}
// 图片后缀获取
public String getExtensionName(String fileName) {
if (fileName == null || fileName.length() == 0) {
return null;
}
int index = fileName.lastIndexOf(".");
if (index < 0 || index > fileName.length() - 1) {
return null;
}
return fileName.substring(index + 1);
}
2、原生JavaScript
实现本地下载
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Documenttitle>
<script type="text/javascript" src="https://cdn.staticfile.org/jquery/3.6.0/jquery.min.js">script>
head>
<body>
<img src="" alt="" id="img">
<input type="button" value="下载" id="btn">
<script>
var scope = {
url: "http://127.0.0.1:8080/user/getBase64Str",
base64: ""
};
$(function () {
$("#btn").click(function () {
// base64图片下载至本地
debugger;
download();
});
// 获取图片 base64
$.get(scope.url, function (resp) {
console.log(resp);
$("#img").attr("src", resp.data);
scope.base64 = resp.data;
}).error(function (e) {
console.log(e);
});
});
function download() {
var date = new Date();
if (!scope.base64) {
return;
}
var aLink = document.createElement("a"); // 创建一个a标签
var blob = base64ToBlob(scope.base64);
var event = document.createEvent("HTMLEvents");
event.initEvent("click", true, true);
aLink.download = date.getTime() + "." + blob.type.split("/")[1]; // 使用时间戳给文件命名
aLink.href = URL.createObjectURL(blob);
aLink.click();
}
// base64转Blob对象
function base64ToBlob(code) {
var parts = code.split(";base64,");
var contentType = parts[0].split(":")[1];
var raw = window.atob(parts[1]);
var rawLength = raw.length;
var uint8Array = new Uint8Array(rawLength);
for (var i = 0; i < rawLength; i++) {
uint8Array[i] = raw.charCodeAt(i);
}
return new Blob([uint8Array], {type: contentType});
}
script>
body>
html>
在来对比图片
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)