Method 1: src points to the location of the image
The most commonly used method, no need to match back-end code
<img src="img/boat.gif" alt="Big Boat">
Method 2: src executes the background path and obtains the byte array of the image
front-end code
<img src="/getImage" alt="Big Boat">
backend code
@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());
}
}
Method 3: src points to the background path and obtains the base64 encoding (string) of the image byte array
Front-end code
<!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>
backend code
@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;
}