方式一:src指向图像的位置
最常用的一种方式,无需搭配后端代码
<img src="img/boat.gif" alt="Big Boat">
方式二:src执行后台路径,获取图片的字节数组
前端代码
<img src="/getImage" alt="Big Boat">
后端代码
@GetMapping("getImage")
public void image(HttpServletResponse response) throws IOException {
try(InputStream input = new FileInputStream("D:\\个人资料\\图片\\Picture\\lf.jpg");
OutputStream output = response.getOutputStream()){
output.write(input.readAllBytes());
}
}
方式三:src指向后台路径,获取图片字节数组的base64编码(字符串)
前端代码文章来源:https://www.toymoban.com/news/detail-727196.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="/static/js/jquery.js"></script>
<style>
.main{
display: flex;
}
.imgdiv{
text-align: center;
margin: 5px;
}
.imgdiv p{
font-weight: bold;
font-size: 22px;
}
img{
width: 200px;
height: 250px;
}
</style>
</head>
<body>
<div class="main">
<div class="imgdiv">
<img id="img1" src="">
</div>
<div class="imgdiv">
<img id="img2" src="">
</div>
</div>
</body>
<script>
$(document).ready(function () {
var params = {
"img1": "dog.jpg",
"img2": "cat.jpg"
};
fetch("/getImage", {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=UTF-8'
},
body: JSON.stringify(params)
}).then(res => res.json()).then(res => {
for (var p in res) {
$("#" + p)[0].src = "data:image/jpg;base64," + res[p];
}
})
});
</script>
</html>
后端代码文章来源地址https://www.toymoban.com/news/detail-727196.html
@PostMapping("getImage")
public Map<String, String> image(@RequestBody Map<String, String> map) throws Exception {
String baseImgUrl = "D:\\个人资料\\图片\\Picture\\";
Map<String, String> imageMap = new HashMap<>();
for (Map.Entry<String, String> entry : map.entrySet()) {
String imageId = entry.getKey();
// 图片名称
String imageName = entry.getValue();
// 最终图片路径
String imgUrl = baseImgUrl + imageName;
try (InputStream input = new FileInputStream(imgUrl)) {
String b64encoded = Base64.getEncoder().encodeToString(input.readAllBytes());
imageMap.put(imageId, b64encoded);
}
}
return imageMap;
}
到了这里,关于img加载图片的三种方式的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!