java 将 byte[] 转换为图像并在 jsp 上显示

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34560229/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 23:02:50  来源:igfitidea点击:

Convert byte[] to image and display on jsp

javahibernatejspspring-mvcimage-uploading

提问by MJM

I'm trying to display an uploaded picture (which is now a byte array) on a jsp page. Now, the byte[] column exists in the database and has to be converted to an image.

我正在尝试在 jsp 页面上显示上传的图片(现在是一个字节数组)。现在,byte[] 列存在于数据库中,必须转换为图像。

This is what I've been trying:

这是我一直在尝试的:

Part of the table on jsp page:

jsp页面上的部分表格:

<c:forEach var="user" items="${userList}">
    <tr>
        <td>${user.fileName}</td>
        <td>
            <img src="data:image/jpg;base64,${user.imageFile}" alt="No image">
        </td>

Part of the controller that takes an array of bytes from a MultipartFile object:

从 MultipartFile 对象中获取字节数组的控制器的一部分:

@RequestMapping(value = "/register", method = RequestMethod.POST)
    public ModelAndView userRegister(@ModelAttribute("user") @Valid User user, BindingResult result, ModelMap model, @RequestParam("fileData") MultipartFile fileData) throws Exception {

            if (!fileData.isEmpty() && fileData != null) {                

                byte[] bytes = fileData.getBytes();
                user.setFileName(fileData.getOriginalFilename());
                user.setImageFile(bytes);
            }
        }

If any additional information is needed, please let me know. Thanks.

如果需要任何其他信息,请告诉我。谢谢。

回答by Master Slave

You can add a tranisent base64imageFileproperty to your User. It will hold the base64 encoded string of the image, which you can access in your jsp like

您可以将瞬态base64imageFile属性添加到您的User. 它将保存图像的 base64 编码字符串,您可以在 jsp 中访问它,例如

<img alt="img" src="data:image/jpeg;base64,${user.base64imageFile}"/>

And in your method you should do the encoding, somethig like

在您的方法中,您应该进行编码,例如

@RequestMapping(value = "/register", method = RequestMethod.POST)
    public ModelAndView userRegister(@ModelAttribute("user") @Valid User user, BindingResult result, ModelMap model, @RequestParam("fileData") MultipartFile fileData) throws Exception {
        if (!fileData.isEmpty() && fileData != null) {                
            byte[] bytes = fileData.getBytes();
            user.setFileName(fileData.getOriginalFilename());
            user.setImageFile(bytes);
            byte[] encodeBase64 = Base64.encodeBase64(bytes);
            String base64Encoded = new String(encodeBase64, "UTF-8");
            user.setBase64image(base64encoded);
        }
    }

IOUtilsand Base64are a handy util classes from org.apache.commons, shouldn't have a problem finding

IOUtils并且Base64是来自 的一个方便的 util 类org.apache.commons,查找应该没有问题