How to Convert BufferedImage to Image for Display on JSP

I would like to convert BufferedImageto an image to be displayed on a JSP page. How can I achieve this?

+5
source share
2 answers

First, JSP is a viewing technology that provides a template for writing HTML / CSS / JS inside and the ability to interact with Java internal code to control page flow and access data to the backend. Your problem is more in HTML.

Now, to display the image on an HTML page, you need an HTML element <img>. To define / highlight an image, you just need to specify the attribute srcon the URL. For example.

<img src="url/to/image.jpg">

( , URL-, , http://)

, , Servlet, url-pattern, URL- . .

<img src="imageservlet/image.jpg">

( , , /imageservlet/*, , , request.getPathInfo())

<img src> GET, doGet() . HTTP , , OutputStream , , (Content-Type, Content-Length / Content-disposition). ImageIO#write() BufferedImage OutputStream.

. Files#copy() ImageIO#write().

response.setContentType("image/png");
ImageIO.write(bufferedImage, "png", response.getOutputStream());

. :

+10

BufferedImage Image, jsp. Java 6 JAXB javax.xml.bind.DatatypeConverter.printBase64Binary(byte[]) String [] base 64. 64 <img html, base 64 i.e. src="data:image/jpg;. .

sample.jsp( ):

<%@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"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
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);
%>

<div>
    <p>As of v6, Java SE provides JAXB</p>
    <img src="data:image/jpg;base64, <%=b64%>" alt="Visruth.jpg not found" />
</div>          
</body>
</html>

IMO, , <img src="data:image/gif;base64,R0lGODlhAQABAIAAAHd3dwAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==" width="200" alt="thumbnail" height="200">. url src, : - <img src="uri-of-image/profile-pic.jpg" width="600" alt="No Profie Pic" height="600">

+4

All Articles