方式一: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编码(字符串)

​前端代码

<!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>

后端代码

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

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐