how to display images and information

how to display images and information(e.g. like questions) on a jsp page that stored in a database
[105 byte] By [rcherniin@rediffmail.coma] at [2007-11-27 1:57:09]
# 1

Usually it looks like:<img src="imageservlet?id=someimageid" />

Some information here

If you want to know how to code, Google around for "[url=http://www.google.com/search?q=imageservlet]ImageServlet[/url]", you'll find lot of examples.

For example: http://balusc.xs4all.nl/srv/dev-jep-img.html

BalusCa at 2007-7-12 1:32:24 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 2

Opps sorry i haven't checked your post BalusC....

Hope i cud be excused for that

Write a ImageServlet which queries the databse and gets the Binarydata and displays an image in return...

Just as an example use the below links

http://balusc.xs4all.nl/srv/dev-jep-img.html

which was created by one of the popular member(With id BalusC) of this Java Forum

http://www.koders.com/java/fid36DD4E9496EB216FD2F4EF95B9201C5D71444B13.aspx

or use http://www.ribomation.com/riboutils/imageservlet/ package

and display contents in the following way

<%@ page language="java" %>

<%

-

-

%>

<HTML>

<BODY>

<!-- HTML or JSP -->

<img src="image?id=<randomid>" />

<%=RandomData5>

</BODY>

</HTML>

Hope this might help :)

REGARDS,

RaHuL

RahulSharnaa at 2007-7-12 1:32:24 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 3
> or use> http://www.ribomation.com/riboutils/imageservlet/> packageThis doesn't load images from DB. It just dynamically creates simple shapes.
BalusCa at 2007-7-12 1:32:24 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 4

well i was not sure of it..:(

how about the one below ?

http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=50&t=014273

I truely understand that is a curde way of doing it...

May be gives a better understanding of doing it 2 OP..

& please excuse me for reposting your ideas....

RahulSharnaa at 2007-7-12 1:32:24 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 5

hai rahul,

thnk for replying me

i got abled to print the images with quesions

now i got a problem to display the images with choices

problem is:

i am storing the images,choice id,choice description and storing into the arraylist and passing to the beans

and trying to retrive those things and display.

all the choices are printing but images are not getting

how to convert image object to relavent thing

will plz help me out

rcherniin@rediffmail.coma at 2007-7-12 1:32:24 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 6

hai rahul,

thnk for replying me

i got abled to print the images with quesions

now i got a problem to display the images with choices

problem is:

i am storing the images,choice id,choice description and storing into the arraylist and passing to the beans

and trying to retrive those things and display.

all the choices are printing but images are not getting

how to convert image object to relavent thing

will plz help me out

rcherniin@rediffmail.coma at 2007-7-12 1:32:24 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 7

Look As far as i can see....

Utlimately every file could be expressed as a bytes buffer.

so say if you have a bean called Choice Bean which is expressed as

public class ChoiceBean{

private String choiceid;

private String choicedesc;

private byte image[];

public void setChoiceId(String choiceid){

this.choiceid = choiceid;

}

public String getChoiceId(){

return this.choiceid;

}

public void setChoiceDesc(String choicedesc){

this.choicedesc = choicedesc;

}

public String getChoiceDesc(){

return this.choicedesc;

}

public void setImage(byte image[]){

this.image = image;

}

public byte[] getImage(){

return this.image;

}

}

QuestionList.java:

===============

public class QuestionList{

private List<ChoiceBean> choicelist;

/*Other member variable declarations*/

-

-

-

public List<ChoiceBean> getChoiceList(){

/*Custom code where you may build the list by querying the DA layer*/

return this.choicelist;

}

public int search(String choiceid){

int index = -1;

for(int i =0 ; i < this.choicelist.size() ; i++){

ChoiceBean cb = this.choicelist.get(i);

if(cb.getChoiceId().equals(choiceid)){

index = i;

break;

}

}

return index;

}

/* Other member method declarations */

-

--

--

}

and you are retreving List<ChoiceBean> from DB using your query & have created a session attribute / <jsp:useBean> named ChoiceList

NOTE: sometimes your application server can go out of bounds as you are consuming a lot of memory by creating an arraylist object.

use the following methodology to display images & choices

sample.jsp:

=========

<jsp:useBean id="QuestionList" class="com.qpa.dao.QuestionList" scope="session"/>

<TABLE>

<%

/* QuestionList.getChoiceList() is a method which fetches data from the DB & returns it in form of List<ChoiceBean> */

List<ChoiceBean> choicelist = QuestionList.getChoiceList();

for(int i =0 ; i < choicelist.size() ; i++){

%>

<TR>

<TD><%!=choicelist.get(i).getChoiceId()%></TD>

<!-- calling servlet which renders an images in JPG format based upon given choiceid(unique field) -->

<TD><IMAGE src="ImageServlet?choiceid=<%!=choicelist.get(i).getChoiceId()%>"/> </TD>

<TD><%!=choicelist.get(i).getChoiceDesc()%></TD>

</TR>

<%

}

%>

</TABLE>

<%

session.remove("QuestionList");

%>

NOTE: usage of JSTL or any other custom built tag-libraries makes life more simpler in the following case

ImageServlet.java:

===============

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

byte buffer[] = null;

HttpSession session = request.getSession(false);

/*getting the QuestionList from the session*/

QuestionList ql = null;

String choiceid = new String("");

try{

choiceid = request.getParameter("choiceid");

/*getting the QuestionList from the session*/

ql = (QuestionList) session.getAttribute("QuestionList");

} catch(Exception exp){

}

if(choiceid.equals("") == false && ql != null ){

List<ChoiceBean> clist = QuestionList.getChoiceList();

/*

assuming that you have created a serach method which searches the entire choice list and would give you

the index of that object which is being refered by unique choiceid and returns -1 if not found

*/

int index = QuestionList.search(choiceid);

if(index != -1){

ChoiceBean cb = clist.get(index);

buffer = cb.getImage();

}

}

if(buffer != null){

// assuming that we have stored images in JPEG format only

JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(new ByteArrayInputStream(buffer));

BufferedImage image =decoder.decodeAsBufferedImage();

response.setContentType("image/jpeg");

// Send back image

ServletOutputStream sos = response.getOutputStream();

JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(sos);

encoder.encode(image);

} else {

response.setContentType("text/html");

response.getWriter().println("<b>Image data not found</b>");

}

}

However,i still feel there are few loopholes with this approach where Application Server can eat up a lot of heap space which may result in outofmemorybound exception.

Hope this might help :)

REGARDS,

RaHuL

RahulSharnaa at 2007-7-12 1:32:24 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 8

Why on earth are you decoding the image and then immediately encoding it back using JPEGImageDecoder/Encoder instead of just gently passing the byte[] in a buffered stream to the response? Do you actually understand the code what you're writing (or maybe it is just brainless copypasting from bad examples)?

Well, you indeed just need to store the image from DB as byte[] property in a DTO. To avoid memory problems, you'd better to store it local on the webserver disk and then use an File property in the DTO to store only the image path/name in.

BalusCa at 2007-7-12 1:32:24 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 9

>(or maybe it is just >brainless copypasting from bad examples)?

Oh !!! Yes i'm ...

>Why on earth are you decoding the image and then immediately >encoding it back using JPEGImageDecoder/Encoder instead of just >gently passing the byte[] in a buffered stream to the response? Do you >actually understand the code what you're writing

The reason why i was encoding it to JPEG is for faster rendering...well with my past knowledge(understading) JPEG is one of the loosy compression techniques. where almost a sample of 8X8 would be replaced by a single pixel.

in the following which i've given i've assumed that user could have stored the binary image data either in classical bitmap formats or JPEG Format.

Though there is a bit overhead involved @ the server side my idea of reducing loading(image rendering) time could be a possiblity.

well to my understading of API documentation(I'd be glad if some one can correct it if that does not do what i want)

JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(new ByteArrayInputStream(buffer));

JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(sos);

encoder.encode(image);

the following code snippet would accept bitmap/jpeg (binary) data & would output JPEG(binary) encoded

which could be more useful for faster at the time of redenring image.

NOTE: There are few more compression techniques which have compression ratio more than that of JPEG like GIF/png(but the only reason why i have used JPEG is beacuse it is widely used over web).

Hope that makes sense.

I'm very much open to correct my ideas if my analysis was wrong on this.

however,it makes lot of sense of the point you are talking about where i may eat lot of memory space consequently.i'd be really glad to keep tht up in mind.

My idea was give OP more options of doing things....and leave it to him of which could be the best suited to him (his requirements)

N sorry for not being methodical of what is being followed widely.

Thanking you !!!

REGARDS,

RaHuL

RahulSharnaa at 2007-7-12 1:32:24 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 10

i tried this code im getting.

but the project is already developed and my portion is to do some enhancements.

He stored the images by converting into binary data and getting again in the form of binary only.

And he used all custom tags in displaying choice id and description.

now i want to display that images with that id and description using cutom tags.

i am typing the sample code of that......

this is working fine and getting all the things exactly....

rs=st.executeQuery("SELECT choice_id,choice_des,answer,weight,image_id FROM exam_apt_choices WHERE ques_id='"+ques_id+"'");

while(rs.next())

{

choice = new ChoiceBean();

choiceimage_id=rs.getInt(5);

if(choiceimage_id!=0)

{

rs_image=st_image.executeQuery("SELECT image from store_image where image_id='"+choiceimage_id+"'");

rs_image.next();

choice_image=rs_image.getBlob(1);

choice.setChoice_image(choice_image);

}

choice.setChoice_id(""+rs.getInt(1));

choice.setChoice_des(rs.getString(2));

choice.setChoiceimage_id(choiceimage_id);

choice_list.add(choice);

ses.setAttribute("choices",choice_list);

every thing he is added to the ArrayList

and the ChoiceBean is

public class ChoiceBean implements Serializable

{

//properties declarations

private String choice_id;

private String ans;

private String choice_des;

private String weight;

private int choiceimage_id;

private Blob choice_image;

// setter methods for properties

public void setChoiceimage_id(int choiceid)

{

choiceimage_id=choiceid;

}

public void setChoice_image(Blob choiceimage)

{

choice_image=choiceimage;

}

public void setChoice_id(String no)

{

choice_id = no;

}

public void setAns(String res)

{

ans = res;

}

public void setChoice_des(String ch)

{

choice_des=ch;

}

public void setWeight(String w)

{

weight=w;

}

//getter methods for properties

public int getChoiceimage_id( )

{

return choiceimage_id;

}

public String getChoice_id()

{

return choice_id;

}

public Blob getChoice_image()

{

return choice_image;

}

public String getAns()

{

return ans;

}

public String getChoice_des()

{

return choice_des;

}

public String getWeight()

{

return weight;

}

}

this is the jsp page where im displaying the questions and choices

im able to display the questions with images

but choice description im able to print but the images....

<logic:present name="choices" scope="session">

<td>

<logic:iterate id="choice" name="choices" >

<tr>

<td class="choices">

<html:multiboxproperty="choice_id" >

<bean:write name="choice" property="choice_id"/>

</html:multibox>

<bean:write name="choice" property="choice_des"/>

</td>

</tr>

<tr><td>

<center>

here im adding the iframe tag to print the image on the same page by calling the LoadChoiceImage.jsp

<iframe name="I1" width="768" height="89" marginwidth="1" marginheight="1" scrolling="no" src="pages/LoadChoiceImage.jsp" border="0" frameborder="0">

Your browser does not support inline frames or is currently configured not to display inline frames.</iframe>

</center>

</td></tr>

</logic:iterate>

</td>

</logic:present>

plz write the code in LoadChoiceImage.jsp

rcherniin@rediffmail.coma at 2007-7-12 1:32:24 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 11

instead of using a jsp pages/LoadChoiceImage.jsp

why don't you use a servlet which does the action of rendering the image

therefore with reference to your code you may structure things in the below way

Expected Jsp

===========

<logic:present name="choices" scope="session">

<td>

<logic:iterate id="choice" name="choices" >

<tr>

<td class="choices">

<html:multiboxproperty="choice_id" >

<bean:write name="choice" property="choice_id"/>

</html:multibox>

<bean:write name="choice" property="choice_des"/>

</td>

</tr>

<tr><td>

<center>

<!-- i am using a image servlet names ImageServlet with a URL mapping /ImageServlet and accepts choiceid as a request parameter -->

<iframe width="768" height="89" marginwidth="1" marginheight="1" scrolling="no" src="ImageServlet?choiceid=<bean:write name="choice" property="choice_id"/> " border="0" frameborder="0"/>

<!- img src="ImageServlet?choiceid=<bean:write name="choice" property="choice_id"/>" name="I1" width="768" height="89" -->

</center>

</td></tr>

</logic:iterate>

</td>

</logic:present>

<% session.removeAttribute("choices");%>

ImageServlet.java:

===============

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.IOException;

import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class ImageServlet extends HttpServlet {

private int search(List<ChoiceBean> clist,String choiceid){

int index = -1;

for(int i=0; i < clist.size(); i++){

if(clist.get(i).getChoiceId().equals(choiceid)){

index = i;

break;

}

}

return index;

}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{

byte buffer[] = null;

String choiceid = new String("");

HttpSession session = request.getSession(false);

List<ChoiceBean> choices = null;

try{

choiceid = request.getParameter("choiceid");

choices = (List<ChoiceBean>) session.getAttribute("choices");

} catch(Exception exp){

exp.printStackTrace();

}

if(!choiceid.equals("") && choices != null){

int index = this.search(choices,choiceid);

if(index != -1){

Blob imagedata = choices.get(index).getChoice_image;

buffer = imagedata.getBytes(1,imagedata.length());

response.setContentLength(buffer.length);

response.setContentType("image/jpeg");

out = new BufferedOutputStream(response.getOutputStream());

out.write(buffer);

out.flush();

/* or

JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(new ByteArrayInputStream(buffer));

BufferedImage image =decoder.decodeAsBufferedImage();

ServletOutputStream sos = response.getOutputStream();

JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(sos);

encoder.encode(image);

*/

} else{

response.setContentType("text/html");

response.getWriter().println("Image Not Found");

}

} else{

response.setContentType("text/html");

response.getWriter().println("Image Not Found");

}

}

}

NOTE: I've assumed that you are storing jpeg images inside the database you may change accordingly & ImageServlet here is not a part of controller(layer) here.

and it would be great if you can make the following servlet bit generic so that you can use it throught your application

Hope this might help :)

however,in terms of scalablity i think your application may suffer.Combining of a Bean with a Blog Field in it & creating a Collection Object of those beans is again an issue wchich might eat up a lot of JVM heap space.the best things which i thnk could be that just use imageid which is already there in the ChoiceBean and send it as a request to the ImageServlet query that DB using the imageid which you have got and get the Blog data at the server end and finally use the blob and output the image stream,

REGARDS,

RaHuL

RahulSharnaa at 2007-7-12 1:32:24 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 12

> byte buffer[] = null;

> buffer = imagedata.getBytes(1,imagedata.length());

> out = new BufferedOutputStream(response.getOutputStream());

> out.write(buffer);

This is not really performant. The unbuffered byte[] will slow down the whole thing. Put the byte[] in a BufferedInputStream. Otherwise the BufferedOutputStream is meaningless.

Just check my ImageServlet example at http://balusc.xs4all.nl/srv/dev-jep-img.html It's technically the best solution available (as in: fastest possible with less possible memory consumption).

Test it yourself with a timed load of images of, say, 10MB in size.

BalusCa at 2007-7-12 1:32:24 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 13

@OP

so as the inputs of the other poster

>Put the byte[] in a BufferedInputStream

you would not do it BufferedInputStream rather you may have to do it with ByteArrayInputStream.(Ref:http://balusc.xs4all.nl/srv/dev-jep-img.html)

therefore replace the following portion

Blob imagedata = choices.get(index).getChoice_image;

buffer = imagedata.getBytes(1,imagedata.length());

response.setContentLength(buffer.length);

response.setContentType("image/jpeg");

out = new BufferedOutputStream(response.getOutputStream());

out.write(buffer);

out.flush();

with

buffer = imagedata.getBytes(1,imagedata.length());

ByteArrayInputStream ip = new ByteArrayInputStream(buffer);

int length = ip.available();

response.setContentLength();

response.setContentType("image/jpeg");

out = new BufferedOutputStream(response.getOutputStream());

while(true){

if(length-- <= 0)

break;

else

out.write(ip.read());

}

out.flush();

@BalusC

>(as in: fastest possible with less possible memory consumption)Test it yourself with a timed load of images of, say, 10MB in size.

Well i truley accept with what you have said.But as far as i can see the user is trying to display images which could be not be more than in odd KiloBytes supposedly. If that is the case there could be an assuption made that he would be more intrested in to faster rendering of the image not the memory consuption.Well i some how fell the solution which you think is the best can suffer the rendering time aspect which is being considered.

(as in: fastest possible with optimal possible memory consumption)

and i think there could be a case where the following could be possible

thing too where i may use technique like static / dynamic paging of the buffer

where given content could be divded into 'N' (where N could be a static / dynamic number) number of parts & then writing it to BufferedOutputStream.

I think this could be much better solution for Larger Images

I'd be glad if you share your inputs on this.

Thanking You !!!

REGARDS,

RaHuL

RahulSharnaa at 2007-7-12 1:32:24 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 14

The point was to buffer it. A ByteArrayInputStream is indeed also buffered.

About the performance, maybe you can care less if it is for a simple webapplication with 100 views per day or so.

But for an real huge loaded enterprise application it makes a big difference.

If you don't code with the performance in mind, then you will get into problems at long term when your small webapp gets popular and become 'slashdotted' ;)

BalusCa at 2007-7-12 1:32:24 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 15
:)Well i don't think OP really cares abt it..Ref:How often you see people making a Collection of Bean Class Instances which has a Blog member and then save it inside the scope of the session.
RahulSharnaa at 2007-7-21 20:16:31 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 16

> where given content could be divded into 'N' (where N could be a static /

> dynamic number) number of parts & then writing it to BufferedOutputStream.

> I think this could be much better solution for Larger Images

Then we have to use threading to load them simultaneously and concatenate them to each other before passing it through one BufferedOutputStream (yes, one).

This is likely 'overthinking'. You'd better to pre-divide the images and put them together in the HTML page with several <img> tags grouped at the right places.

As Java is multithreaded, in this case just multiple instances of ImageServlets will work together.

BalusCa at 2007-7-21 20:16:31 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 17

i got to display the choice images also thank getting me out of that

and one more thing is that how to get the value of bean:write into the user variable

eg..

<bean:write name="choice" property="choiceimage_id"/>

<%int choiceimageid="<bean:write name='choice' property='choiceimage_id'"/>

this is not correct i think

i want the value of choiceimage_id into user variable so that i can display the iframe on condition.

now it is displaying iframe whether the image is there or not.

i want to display the iframe only when image is there.

rcherniin@rediffmail.coma at 2007-7-21 20:16:31 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 18
how to display the special characters on jsp page like square root, alpha, beta ,sigma like these type of characters i to display on page.i want to use any ascii codes for these characters can u tell me ........
rcherniin@rediffmail.coma at 2007-7-21 20:16:31 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 19

i got to display the choice images also thank getting me out of that

and one more thing is that how to get the value of bean:write into the user variable

eg..

<bean:write name="choice" property="choiceimage_id"/>

<%int choiceimageid="<bean:write name='choice' property='choiceimage_id'"/>

this is not correct i think

i want the value of choiceimage_id into user variable so that i can display the iframe on condition.

now it is displaying iframe whether the image is there or not.

i want to display the iframe only when image is there

rcherniin@rediffmail.coma at 2007-7-21 20:16:31 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 20
how to display the special characters on jsp page like square root, alpha, beta ,sigma like these type of characters i to display on page.i want to use any ascii codes for these characters can u tell me ........
rcherniin@rediffmail.coma at 2007-7-21 20:16:31 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 21

i got to display the choice images also thank getting me out of that

and one more thing is that how to get the value of bean:write into the user variable

eg..

<bean:write name="choice" property="choiceimage_id"/>

<%int choiceimageid="<bean:write name='choice' property='choiceimage_id'"/>

this is not correct i think

i want the value of choiceimage_id into user variable so that i can display the iframe on condition.

now it is displaying iframe whether the image is there or not.

i want to display the iframe only when image is there.

rcherniin@rediffmail.coma at 2007-7-21 20:16:31 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 22

why don't you use "<bean:define/>" here.I'm assuming that form bean named "choice" is of type ChoiceFormBean(class).

<bean:define id="choiceObj " name="choice" />

<%

int choiceid = ((ChoiceFormBean) choiceObj).getChoiceimage_id();

%>

or

<bean:define id="choiceObj " name="choice" type="ChoiceFormBean" />

<%

int choiceid = choiceObj.getChoiceimage_id();

%>

Hope that helps.If it does don't forget to assign duke stars which you have promised. :)

REGARDS,

RaHuL

RahulSharnaa at 2007-7-21 20:16:31 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 23
when question contains some special characters like like square root, alpha, beta ,sigma like these type of characters i to display on page. how can i display on a jsp page is there any function for that i want to use any ascii codes for these characters can u tell me
rcherniin@rediffmail.coma at 2007-7-21 20:16:31 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...