0

在我的应用程序中,我有一个上传的功能。为此,我使用了 apache-commons 文件上传和 spring multipart,并将图像存储在目录文件夹中(不在项目上下文中)。我卡住的问题是获取图像并将其渲染到 jsp 上。我尝试使用缓冲图像和 ImageIO 从该文件夹中读取图像,但无法弄清楚如何使用 img 标签在 jsp 中渲染它。任何帮助,将不胜感激。

//Code for reading 
BufferedImage im=ImageIO.read(new File(imagePath));
4

1 回答 1

3

最后能够使用 img 标签在网络浏览器上显示图像。我现在遵循的步骤: 1. 我使用 BufferedImage 读取图像。2.使用ByteArrayOutputStream将bufferedImage转换为字节。3.使用 apache commons codec lib 将该流编码为 Base64 并转换为字符串 4.使用 img 标签在 html 上返回该图像的字符串值

 //Pseudo Code 
    BufferedImage bufferedImage=ImageIO.read(new File(imagePath));

   //imageDao contains the image name that i stored in the database
   String []formatSplit=imageDao.split("\\.");

   if(formatSplit.length==2){
     String format=formatSplit[1];

     //ImageUtility is class that contain code for converting bufferedimage to string
     String traineeImage=ImageUtility.encodeToString(bufferedImage,format );

     model.addAttribute("imagePath", traineeImage);
    }


    //ImageUtilty class -method

     public static String encodeToString(BufferedImage image, String type) {

        String imageString=null;
        String encodedImage=null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        try {

            ImageIO.write(image, type, bos);
            byte[] imageBytes = bos.toByteArray();


            encodedImage=org.apache.commons.codec.binary.Base64.encodeBase64String(imageBytes);

            imageString = "data:image/"+type+";base64,"+encodedImage;

            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return imageString;
    }

在 img 标签 src 属性中,我通过了 imageString 并且它起作用了。为了找到解决方案,我从 stackoverflow 和其他博客中找到了很多提示,这些提示帮助我实现了我正在寻找的东西。谢谢。

于 2013-11-28T07:03:49.283 回答