I am a beginner when it comes to jsp, so sorry if the code is really bad.

I need to be able to convert images to and from byte[] to store and display images, but I am not sure how to do it.

I have a form first for uploading the image:

<form method="post" action="saveProfileImage.jsp">
<tr><td><%=profileImageText %>:</td></tr>
<tr><td><input type="file" name="filename" /></td></tr>
<tr><td><input type="submit" value="<%= uploadImageText %>" /></td></tr>

And here is part of saveProfileImage.jsp:

File f = new File(request.getParameter( "filename" ));

BufferedImage img = ImageIO.read(f);
ByteArrayOutputStream bas = new ByteArrayOutputStream();
ImageIO.write(img, "png", bas);
byte[] data = bas.toByteArray();

us.setProfileImage(p, data);

I am not sure if this is the correct way to convert the image to byte[].
But the us.setProfileImage() sends the byte[] to the database, so I do not need to worry about that part.

What I really have trouble with is how to display the image. I have a method getProfileImage() which returns the byte[], but I don't know how to convert it so I can display it on a jsp page.

This is what I have done so far on that end:

ImageIcon image = null;
byte[] barr = us.getProfileImage(p);
if(barr != null){
image = new ImageIcon(barr);

But I suppose I cannot display an ImageIcon on a jsp page and I don't know how else to convert it.

Any help would be much appreciated.

7 Years
Discussion Span
Last Post by jwenting

You can't do that, period.
The output of an http request is ALWAYS a single content type, you can NOT mix text and binary content in a single response.
You're going to have to have a JSP contain a link to an image, which might be a servlet that produces that image as a separate request.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.