How to display image returned from servlet?

Currently: I am getting an image from a database and displaying it using the below code.
Desired: I want to display HTML also, not just the image.
response.setContentType("image/jpg");
ServletOutputStream out = response.getOutputStream();       
java.io.InputStream in = DatabaseClass.getImageStream(image_name);       
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int length = 0;
while ((length = in.read(buffer))!=1)
  out.write(buffer,0,length);
in.close();
out.flush();
out.close();I have read about doing this with the image tag (<img src=name.jpg), but this requires storing the image in a file on the server...which is not what I want.
Any/All suggestions appreaciated. Thanks!

The <img> tag doesn't necessarily require storing the image on the server. You can just as easily do this:
<img src="/servlet/imageServlet" width="320" height="240" alt="My image" />

Similar Messages

  • How to display image using from open dialog box?

    I've developed a program that can display image by named the file that I want to display in my program.
    But how can I display an image from an Open Dialog Box?
    I attch here with my program.
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.filechooser.*;
    public class SuDisplayTool6 extends JFrame implements InternalFrameListener,ActionListener
    JTextArea display1;
    JDesktopPane desktop;
    JInternalFrame displayWindow;
    JInternalFrame listenedToWindow;
    static final String SHOW = "Show Image";
    static final int desktopWidth = 800;
    static final int desktopHeight = 600;
    private static final int kControlX = 88 ;
    private DrawingPanel panel;
    public SuDisplayTool6(String title)
    super("Internal Frame");
    desktop = new JDesktopPane();
    desktop.putClientProperty("JDesktopPane.dragMode","outline");
    desktop.setPreferredSize(new Dimension(desktopWidth, desktopHeight));
    setContentPane(desktop);
    addMenu();
    createDisplayWindow();
    desktop.add(displayWindow);
    Dimension displaySize = displayWindow.getSize();
    displayWindow.setSize(desktopWidth, displaySize.height);
    protected void createDisplayWindow()
    JButton b1 = new JButton("Show Image");
    b1.setActionCommand(SHOW);
    b1.addActionListener(this);
    display1 = new JTextArea(3,30);
    display1.setEditable(false);
    JScrollPane textScroller = new JScrollPane(display1);
    textScroller.setPreferredSize(new Dimension(200,75));
    textScroller.setMinimumSize(new Dimension(10,10));
    displayWindow = new JInternalFrame("Header Graph",true,false,true,true);
    JPanel contentPane = new JPanel();
    contentPane.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
    contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
    contentPane.add(Box.createRigidArea(new Dimension(0,5)));
    contentPane.add(textScroller);
    b1.setAlignmentX(CENTER_ALIGNMENT);
    contentPane.add(b1);
    displayWindow.setContentPane(contentPane);
    displayWindow.pack();
    displayWindow.show();
    protected void createListenedToWindow()
    listenedToWindow = new JInternalFrame("Image",true,true,true,true);
    listenedToWindow.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
    listenedToWindow.setSize(800,450);
    panel = new DrawingPanel();
    listenedToWindow.setContentPane(panel);
    public void internalFrameClosing(InternalFrameEvent e)
    public void internalFrameClosed(InternalFrameEvent e)
    listenedToWindow = null;
    public void internalFrameOpened(InternalFrameEvent e)
    public void internalFrameIconified(InternalFrameEvent e)
    public void internalFrameDeiconified(InternalFrameEvent e)
    public void internalFrameActivated(InternalFrameEvent e)
    public void internalFrameDeactivated(InternalFrameEvent e)
    public void actionPerformed(ActionEvent e)
    if (e.getActionCommand().equals(SHOW))
    if (listenedToWindow == null)
    createListenedToWindow();
    listenedToWindow.addInternalFrameListener(this);
    desktop.add(listenedToWindow);
    listenedToWindow.setLocation(desktopWidth/2 - listenedToWindow.getWidth()/2,
    desktopHeight - listenedToWindow.getHeight());
    listenedToWindow.show();
    else
    public static void main(String[] args)
    JFrame frame = new SuDisplayTool6("Su Display Tool");
    frame.addWindowListener(new WindowAdapter()
    public void windowClosing(WindowEvent e)
    System.exit(0);
    frame.pack();
    frame.setVisible(true);
    private void addMenu()
    JMenuBar menuBar;
    JMenu menu, submenu;
    JMenuItem menuItem;
    final JFileChooser fc = new JFileChooser();
    fc.addChoosableFileFilter(new ImageFilter());
    menuBar = new JMenuBar();
    setJMenuBar(menuBar);
    menu = new JMenu("File");
    menuBar.add(menu);
    menuItem = new JMenuItem("Open...");
    menu.add(menuItem).addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    int returnVal = fc.showOpenDialog(SuDisplayTool6.this);
    menuItem = new JMenuItem("Save");
    menu.add(menuItem);
    menuItem = new JMenuItem("Save As...");
    menu.add(menuItem).addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent e)
    int returnVal = fc.showSaveDialog(SuDisplayTool6.this);
    menuItem = new JMenuItem("Close");
    menu.add(menuItem);
    menu.addSeparator();
    menuItem = new JMenuItem("Exit");
    menu.add(menuItem).addActionListener(new WindowHandler());
    menu = new JMenu("Edit");
    menuBar.add(menu);
    menu = new JMenu("View");
    menuBar.add(menu);
    menuItem = new JMenuItem("Zoom In");
    menu.add(menuItem);
    menuItem = new JMenuItem("Zoom Out");
    menu.add(menuItem);
    menu.addSeparator();
    submenu = new JMenu("Header");
    menuItem = new JMenuItem("CDPX");
    submenu.add(menuItem);
    menuItem = new JMenuItem("SX");
    submenu.add(menuItem);
    menuItem = new JMenuItem("CX");
    submenu.add(menuItem);
    menu.add(submenu);
    menu = new JMenu("Help");
    menuBar.add(menu);
    menuItem = new JMenuItem("About");
    menu.add(menuItem).addActionListener(new WindowHandler());
    private class WindowHandler extends WindowAdapter implements ActionListener
    public void windowClosing(WindowEvent e)
    System.exit(0);
    public void actionPerformed(ActionEvent e)
    if(e.getActionCommand().equalsIgnoreCase("exit"))
    System.exit(0);
    else if(e.getActionCommand().equalsIgnoreCase("About"))
    JOptionPane.showMessageDialog(null,"This program is written by Nenny Ruthfalydia.","About",JOptionPane.PLAIN_MESSAGE);
    class DrawingPanel extends Panel
    final ImageIcon imageIcon = new ImageIcon("image8.jpg");
    Image image = imageIcon.getImage();
    public void paint (Graphics g)
    g.drawImage(image, 10, 10, this);

    so much wrong with this post...
    a) use the code tags to format the code. Now it is an unreadable mess
    b) scriptlets in your JSP. I don't even want to look at that mess. Learn how to combine servlets and JSPs to create clean, readable and maintainable code in which view logic and business logic are separated. The rule: no java code in your JSP, only tags and EL expressions (learn about JSTL).
    So you get a blank screen. When you do "view source" in your browser, do you see anything there? If nothing, check if you are behind a proxy server. The solution to a post of not too long ago was that the blank screen was being caused by faulty proxy server settings (the user figured it out himself, I don't know what was done to solve it).
    If all this fails you will have to do some debugging magic using your favorite IDE. It will probably be something stupid you are overlooking in the code. It is annoying, but debugging code that does not work is a big part of your job. Better get good at it.

  • How to display images on a servlet generated page???

    Hi, I am developing an app in which I must display some messages, each message may have an image. The images are saved in the database. I do not want to save the image on the filesystem but instead of that I want to send the image as an attribute to the page but I dont know then how to display it. I have no idea about how to do that! Any help on this would be very appreciated!

    mmm yes I know that the img tag displays an image but I am asking how to display the image without saving the file into the server filesystem, I mean something like:
    1.- getting the bytes from the Database
    2.- getting an Image object
    3.- pasing it to the request as an attribute
    4.- getting that attribute from the request
    5.- displaying it on somehow directly from the image var or something.
    the src parameter of the img tag takes as a string the path of the image, but i dont want to save it.

  • How to display image file from the link in the field

    Hi all,
    I have a column where it keeps the link of the image files reside. The link will be in the server such as \\server\picture1.jpg
    I have try to code in Read_Image_File('\\server\picture1.jpg', 'ANY','OM_ITEM.ITEM_URL');
    But I was encountered error run, ORA-01465: invalid hex number.
    Any one please help me. Thanks.
    Regards,
    Lim

    There are tons of informations missing here, for instance (but not limited to) the exact forms version you are using (note: 10g is not a version, but 10.1.2.0.2 is). Without Version informations a correct answer is not possible
    You might want to go through the links from the Announcement entitled "<a href=http://forums.oracle.com/forums/ann.jspa?annID=432>Before posting on this forum please read </a>" which contains links to the documentation and instructions on how to post proper questions for example.
    cheers

  • How to read bytes(image) from a server ?how to display image after read byt

    How to read bytes(image) from a server ?how to display image after reading bytes?
    i have tried coding tis , but i couldnt get the image to be display:
    BufferedInputStream in1=new BufferedInputStream(kkSocket.getInputStream());
    int length1;
    byte [] data=new byte[1048576];
    if((length1=in1.read(data))!=-1){
    System.out.println("???");
    }System.out.println("length "+length1);
    Integer inter=new Integer(length1);
    byte d=inter.byteValue();

    didn't I tell you about using javax.imageio.ImageIO.read(InputStream) in another thread?

  • Display PDF document from Servlets to browser - how 2 change the title

    Hi, need help of changing the html title when Display PDF document from Servlets to browser. By default the browser's title shows the obsolute URL where the rdf comes from (i.e. http://www.google.com/sample.pdf), because servlet responds a binary data (PDF), there seems to be no other way to change the browser's title to fit my own choice.
    Appreciate your quick help,

    You can try and check with
    .setTitle("Welcome");

  • 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

    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

  • Problem with image returned from getGeneratedMapImage method

    I'm a newbie as far as map viewer and Java 2D goes....
    My problem is the java.awt.Image returned from the getGeneratedMapImage method of the MapViewer API. The image format is set to FORMAT_RAW_COMPRESSED. The image returned is of poor quality with colors not being correct and lines missing. I'm painting the Image returned from this method onto my own custom JComponent by overriding the paint() method...
    public void paint( Graphics g )
    Image image = map.getGeneratedMapImage();
    if ( image != null )
    g.drawImage( image, getLocation().x, getLocation().y, Color.white, this );
    If I take the xml request sent to the application server and paste it into a "sample map request" on the map admin website (along with changing format to PNG_STREAM) my image renders exactly how I expect it to.
    Anyone have any idea what I need to do to get the java.awt.Image with format set to FORMAT_RAW_COMPRESSED to render correctly. I was hoping to get back a BufferedImage or a RenderedImage from the getGeneratedMapImage call but I'm getting back a "sun.awt.motif.X11Image".
    Will downloading the JAI (java advanced imaging) from sun help me at all?

    Joao,
    Turns out it is related to colors. I'm dynamically adding themes, linear features and line styles. I ran a test where I changed the color being specified in the line style from magenta (ff00ff) to black. When I changed the color the linear feature would show up. It was being rendered as white on a white background when I was specifying it to be magenta. I'm specifying another linear feature to be green and it is showing up in the java image as yellow. This doesn't happen when I take the generated XML from the request and display it as a PNG_STREAM.
    Any clue what is going on there?
    Jen

  • Can display Web pages from servlet but not applet?

    I have been able to display real-world Web pages from a simple servlet using JDeveloper 3.0, but can't figure out how to do the same from an applet. Any hints?

    My previous post had the detail...Probably a simple question from a relative novice. I'm having a problem just viewing web pages by calling them from a "list" of URLs in an applet. I built an applet with a split pane that has a JTree on one side and an "HTML viewing pane" on the other. I can click JTree nodes to display local html files, but I don't understand how to display web pages from the Internet. Do I need something like HyperlinkListener to make the jump to "hyper-world"???

  • How to display images on my internal isight?

    Hi,
    I just bought the new iMac 2 gig dual. Running on 10.5.2.
    I wanted to know how to display images on my screen during a video conference chat without resorting to holding up a print out to the camera? I need something where I can switch from video mode to image mode and show a single image at a time if I need to. All that while still talking of coarse. If it isn't possible with my iSight software, can you point me to other software I can download and still use my built in cam?
    I hope I was clear enough in asking this.
    Thanks
    Liban

    Welcome to Apple Discussions, Liban
    iChat can do what you want, but I do not know of any web-based video chat site that can.
    Look for Help or Support information on the site you are using or ask the Webmaster if his site has the capability to do what you want.
    EZ Jim
    PowerBook 1.67 GHz w/Mac OS X (10.4.11) G5 DP 1.8 w/Mac OS X (10.5.2)  External iSight

  • How to display image?

    Hi all,
    How to display image from the database table in the adobe form by using web dynpro abap?
    I want to display image in the adobe interactive form by using web dynpro abap.
    Please help me.
    Regards,
    srini

    Hi Srini,
    If you go through the article you might have seen the following piece of code
    *** Send the values back to the node
      lo_el_z_if_test_cv->set_static_attributes(
        EXPORTING
          static_attributes = ls_z_if_test_cv ).
    " here ls_z_if_test_cv has the image in XSTRING format which has beeen retrived using METHOD get_bds_graphic_as_bmp of CLASS cl_ssf_xsf_utilities
    " In  your case you need to just use the select query n fetch it from your table; ( provided your image is store in XSTRING format )
    How is your image stored in your database table ?
    Regards,
    Radhika.

  • I cannot display image (read from oracle BLOB field) on browser?

    I cannot display image (read from oracle BLOB field) on browser?
    Following is my code, someone can give me an advise?
    content.htm:
    <html>
    <h1>this is a test .</h1>
    <hr>
    <img  src="showcontent.jsp">
    </html>showcontent.jsp:
    <%@ page import="com.stsc.util.*" %>
    <%@ include file="/html/base.jsp" %>
    <% 
         STDataSet data = new STDataSet();
    //get blob field from database     
         String sql = "SELECT NR FROM ZWTAB WHERE BZH='liqf004' AND ZJH='001'";
         //get the result from database
         ResultSet rs = data.getResult(sql,dbBase);
         if (rs!=null && rs.next()) {
              Blob myBlob = rs.getBlob("NR");
              response.setContentType("image/jpeg");//
              byte[] ba = myBlob.getBytes(1, (int)myBlob.length());
              response.getOutputStream().write(ba);
              response.getOutputStream().flush();
         // close your result set, statement
         data.close();     
    %>

    Don't use jsp for that, use servlet. because the jsp engine will send a blank lines to outPutStream corresponding to <%@ ...> tags and other contents included in your /html/base.jsp file before sending the image. The result will not be treated as a valid image by the browser.
    To test this, type directly showcontent.jsp on your browser, and view it source.
    regards

  • How to display image in database using html or php

    i've try already to work this thing but i can't do it. anyone that can help me or give me any example or reference to resolve my problem to retrieve or display image(blob) from database. hope that all of you help me

    Using JHeadstart, you can display a BLOB column from the database in HTML, by way of ADF. Check out the JHeadstart Tutorial at http://www.oracle.com/technology/products/jdev/tips/muench/jhstutorial/index.html to get started, then do the same for your own database tables that include the BLOB column. JHeadstart will take care of rendering it as a file upload or image, depending on the display type you set at the attribute level.
    Hope this helps,
    Sandra Muller
    JHeadstart Team
    Oracle Consulting

  • How to display multiple tables from database using netbeans swing gui

    plz reply asap on how to display multiple tables from database using netbeans swing gui into the same project

    Layered Pane with JTables or you can easily to it with a little scripting and HTML.
    plzzzzzzzzzzzzzzzzz, do not use SMS speak when posting.

  • How to display the data from database(MS access) to a textbox

    anyone know ?

    how to display the data from database(MS access) to a
    textboxThe reply hasn't changed over these years. Read the tuutorial on how to fetch the data. You can display it anywhere you feel like. :)
    http://java.sun.com/docs/books/tutorial/jdbc/

Maybe you are looking for

  • WRT54G and Windows 7

    I have a WRT54G v6 with the most up-to-date firmware installed.  I upgraded to Windows 7 and this is what is happening:  The computer can be OFF, and all my devices (iPod touch, laptop) can get on my network and everything works fine on those devices

  • Create sales revenue account in SAP R/3

    Hi there,             I need to find the path for creating "sales revenue account" and "sales revenue deductions account" in SAP R/3 I will appreciate suggestions for the same. Thanks Nishant

  • Thumnails won't load, how do I fix this?

    Suddenly, after years of workin in Lightroom 3 on same computer (PC OS is Windows 7), thumbnails will not load. Some will, but seemingly randomly, 95% of them will not from any of numerous external drives nor PC drive. loading ...... keeps showing on

  • IPod Touch and iHome Alarm Clock

    We were just given an iHome (iH4B) alarm clock for iPod. The specs state that it is compatible with the 2g 16gb Touch that we have. However when it is time for the alarm, the music stops after about 30 seconds and is replaced with alarm beeps. I thin

  • Pbfetch - Please not another AUR frontend

    pbfetch is an AUR frontend and optionally a Pacman wrapper. Background and Motivation I originally intended to keep pbfetch private, as there are already so many AUR frontends but, after using it for a bit I've decided to let others use, change, beli