How to convert BufferedImage to image to display on JSP

后端 未结 2 1684
盖世英雄少女心
盖世英雄少女心 2020-11-29 10:31

I would like to convert BufferedImage to an image that will display on JSP page. How can I achieve this?

2条回答
  •  感动是毒
    2020-11-29 11:09

    You need not convert BufferedImage to Image to display it on the jsp page. Because, Java 6 JAXB provides javax.xml.bind.DatatypeConverter.printBase64Binary(byte[]) String to convert byte[] in to base 64 string. The base 64 string can be displayed using the html tag by specifying the source data as base 64 i.e. src="data:image/jpg;. Here is the sample program referred from this post.

    sample.jsp (test passed) :

    <%@page import="java.awt.image.BufferedImage"%>
    <%@page import="javax.imageio.ImageIO"%>
    <%@page import="java.io.*"%>
    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
    
    
    
    
    Insert title here
    
    
    <%
    BufferedImage bImage = ImageIO.read(new File("/home/visruth/Desktop/Visruth.jpg"));//give the path of an image
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write( bImage, "jpg", baos );
    baos.flush();
    byte[] imageInByteArray = baos.toByteArray();
    baos.close();
    String b64 = javax.xml.bind.DatatypeConverter.printBase64Binary(imageInByteArray);
    %>
    
    

    As of v6, Java SE provides JAXB

    Visruth.jpg not found

    IMO, this approach is perfect for small sized images like thumbnail. Otherwise using direct url of the image will be fine in src attribute eg:- No Profie Pic

提交回复
热议问题