How to retrieve am image from database

hi ,
i hav a requirement that, i hav to store and retrive an image from database(postgresql)and palce it on JLabel.i successfully stored an image into database .while retrieving an image from database im not getting the image .please any one can help me how to retrieve an image and place it in JLabel.
This the code for inserting an image:
Class.forName("org.postgresql.Driver");
Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost:port/database", "username", "pwd");
System.out.println("Connection established");
String INSERT_PICTURE = "insert into imagedata(imageid,data) values (?, ?)";
FileInputStream fis = null;
PreparedStatement ps = null;
try {
conn.setAutoCommit(false);
File file = new File("photo.jpg");
fis = new FileInputStream(file);
ps = conn.prepareStatement(INSERT_PICTURE);
ps.setInt(1, 2);
ps.setBinaryStream(2, fis, (int) file.length());
ps.executeUpdate();
conn.commit();
catch(Exception ex)
ex.printStackTrace();
finally {
ps.close();
fis.close();This is the code for retrieve an image :
Class.forName("org.postgresql.Driver");
Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost:port/database", "username", "pwd");
byte[] imgbytes = null;
String INSERT_PICTURE = "select imageid,data from imagedata ";
Statement stmt=(Statement) conn.createStatement();
try {
ResultSet rs=stmt.executeQuery(INSERT_PICTURE);
while(rs.next())
System.out.println(rs.getString(1));
InputStream file=rs.getBinaryStream(2);
System.out.println("FILE : "+file);
catch(SQLException a)
finally {
stmt.close();please anyone can help meee
thanks

You basically save a File to the database, so you can just re-write the data from the file back temporarily and load it into the application using the ImageIO class
// create necessary connection and statement objects
// retrieve image column
ResultSet rs = stmt.executeQuery("SELECT Image FROM dataTable");
rs.next();
Blob imageData = rs.getBlob("Image");
if( imageData != null ) {
    try {
        File tmpFile = new File("tmpImage");
        FileOutputStream fos = new FileOutputStream(tmpFile);
            fos.write( imageData.getBytes(1L, (int)imageData.length()) );
            fos.close();
        tmpFile.deleteOnExit();
        ImageIcon icon = new ImageIcon( ImageIO.read(tmpFile) );   
        JOptionPane.showMessageDialog(null, icon);
    } catch(IOException ioe) {
        ioe.printStackTrace();
        JOptionPane.showMessageDialog(null, "Failed To Load Image Data", "Load Error",
                JOptionPane.ERROR_MESSAGE);
}ICE

Similar Messages

  • How to retrive multiple images from database

    Hi,
    I have to retrieve multiple images from oracle database and have to display the image in the jsp.
    I am passing imageCategoryId from the jsp.This id contain number of image in DB.
    I googled the issue and i found some solution.want to know whether what i did is correct and how i have to display the retrieved image in jsp.
    Need urgent help.Experts kindly help me.
    This is my action file.
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.naming.NamingException;
    import com.image.dao.ImageDAO;
    public class GetImageServlet extends HttpServlet{
    public void doPost(HttpServletRequest req, HttpServletResponse res)
    throws ServletException, IOException{
    try{
         ImageDAO image = new ImageDAO();
    String categoryId = request.getParameter("catgId");
         bytes[] imagebyte = image.getImagesByCategoryId(categoryId);
    InputStream is = new FileInputStream(imagebyte);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    bos.write(imagebyte);
    blobIs.close();
    catch(IOException e){
    e.printStackTrace();
    } catch(Exception excep) {
                        excep.printStackTrace();
    This is DAO file
    public byte[] getImagesByCategoryId(String categoryId) throws Exception
              PreparedStatement statement = null;
              ResultSet resultSet = null;
              StringBuffer queryBuffer = new StringBuffer();
              Blob image = null;
              String imageId = null;
              ArrayList imageIdLIst = new ArrayList();
              try {
                   this.connection = connManager.getDataSourceConnection();
                   queryBuffer.append("select image from Image_Table where image_category='"+categoryId+"'");
                   statement = connection.prepareStatement(queryBuffer.toString());
                   resultSet = statement.executeQuery();
                   while(resultSet.next()) {
                        image = rs.getBlob(1);
                        long imgLength = image.getBufferSize();
                        byte[] byteImage = new byte[imgLength];
                        byteImage = image.getBytes(1,(int)imgLength);
              } catch(Exception excep) {
                   excep.printStackTrace();
              return byteImage;
    How to display retrieved image in jsp.
    whether action and dao file is correct or what changes i have to do to correct the problem.
    P.S : As a Newbie i dont know how to use code tag for this java code.Kindly forgive me.
    Regards,
    hardlyUsed.

    hardlyused wrote:
    I have to retrieve multiple images from oracle database and have to display the image in the jsp.There are at least two parts to the problem.
    1. Get it from the database.
    2. Display it.
    Part 1 has nothing to do with part 2.
    You must solve 1 before you solve 2.
    Finally generically there is no such thing an "image" but rather there is binary data which is represented in such a way that it one of many formats that represent an "image".
    Knowing which specific format the "image" is stored in will at a minimum be helpful and could be required.

  • Retrieve multiple images from database to servlet

    Hi there,
    I try to retrieve more than one images from database to Servlet/JSP . However, I get only one images in the result set. Here is my code. Please Help .
    How do I display more than one images ( multiple rows ) from database to Servlet ?.
    When I retrieve, I got 3 rows of binary data, but I don't know how to display it on the Servlet/JSP pages.
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.io.*;
    import java.util.*;
    import java.lang.*;
    import java.sql.*;
    import com.sybase.jdbcx.*;
    public class RetrievePhoto extends HttpServlet {
    static ResultSet rs;
    static CallableStatement NGSstmt = null;
    static Connection NGScon = null;
    static SybDriver _driver = null;
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws
    ServletException, IOException {
    ServletOutputStream os = res.getOutputStream();
    String driver = ""
    String URL = "";
    String Host = "";
    String UN = ""; //assign your username here
    String PW = ""; //assign your password here
    try {
    Class c = Class.forName( driver );
    _driver = (SybDriver) c.newInstance();
    DriverManager.registerDriver( (SybDriver) _driver );
    NGScon = DriverManager.getConnection( URL + Host, UN, PW );
    } catch ( SQLException e ) {
    os.println( "Unable to load the Sybase JDBC driver. " + e.toString() );
    e.printStackTrace(System.out);
    } catch (java.lang.Exception ex) {
    // Got some other type of exception. Dump it.
    os.println("Exception - java lang " + ex.getMessage() );
    String PID = req.getParameter("PID"); //passing parameters from Servlet
    try {
    String SQLcmd = "{call RET_PHOTO_BY_PID(?)}";
    NGSstmt = NGScon.prepareCall( SQLcmd );
    //execute the query
    synchronized (NGSIDBstmt)
    NGSstmt.setString(1, PID); //passing parameter to store procedure
    rs = NGSstmt.executeQuery();
    byte[] stuff = new byte[1024];
    int bytesRead = 0;
    res.setContentType("image/gif");
    InputStream is = null;
    // Get the first row
    while( rs.next() ) {
    is = rs.getBinaryStream("PHOTO");
    res.setContentLength(is.available());
    for (int i=0;; i++) {
    bytesRead = is.read(stuff);
    os.write(stuff);
    if ( bytesRead == -1 ) break;
    rs.close();
    os.flush();
    os.close(); //close outputstream
    } catch ( SQLException sqle) {
    os.println("Error in SQL2Exception" + sqle.getMessage());

    When I retrieve, I got 3 rows of binary data, but I don't know how to display it on the Servlet/JSP pages.I will pick this bit of your post, because you seemed to have several partly-overlapping questions.
    You are going about this wrong. You need to decide what your HTML will look like before you start writing servlet code. In this case you want to have something like a table, with an image in each row, right? Now what does the HTML for that look like? It's a <table> element, and so on, but what about the images? Well this is HTML, so it can't contain the binary images. It has to contains links to the images, and the browser will download the image from each of those links and put all of the downloads together into the page it displays.
    That means you can't do it all with one servlet. You need a main servlet that generates the HTML, with the <table> element and the links to the images. Probably you need some DB calls here to find out how many images you're going to have, but you don't need to get them in this servlet. You just need to generate a link for each of them.
    Then you need a second servlet that gets an image. It's going to get a single row from the DB and return the binary image you read from that row. Make sure to use "image/jpg" or whatever's appropriate instead of "text/html" in your response's content type here.
    I will leave you to carry on from here. First step is to design the HTML that your main servlet will produce; remember that the links it generates need to carry enough information for the second servlet to be able to find the right image in the DB.
    PC&#178;

  • How to display an image from database

    Hi all,
    I've saved an image(jpeg file) as BLOB item in the database through the forms.I need to fetch that particular image from the database and display the image in the report.How can i do that?
    I tried to fetch the column from the database and added a text item and selected the PHOTO column , the properties has changed once i selected the BLOB item.File format I changed to Image , But the width is 4 and I'm not able to change that.
    While executing I'm getting two errors,
    REP : 0069 Internal Error
    REP : 62203 Internal Error reading the image - Unable to render RenderedOp for this operation
    Please help me to solve this issue.
    Thanks in advance...

    Hello,
    Try to revert to the "old" way to render images :
    http://www.oracle.com/webapps/online-help/reports/10.1.2/topics/htmlhelp_rwbuild_hs/rwrefex/envvars/envvar_reports_default_display.htm
    To revert to the dependency on DISPLAY and use screen fonts (old font look up algorithm):
    Set REPORTS_DEFAULT_DISPLAY=NO.
    Remove the screenprinter.ppd entry in the uiscreenprint.txt file.
    Set the DISPLAY variable to the active X-Windows display surface.
    Regards

  • How to insert, select image from database

    can any one help me to store and retrive image from mySQL database....
    plz can any one send me code for this ?
    thank you

    First of all, I suggest not to do this!! Creates to much overhead on your database. Especially if you have large images that your going to put in the database.
    Otherwise what you could do is create a BLOB that contains the bytes to your image and insert that into your database.

  • How to retrieve/gather images from a non-ZEN server?

    Our main ZENworks server is 4.01 and it's running out of space for
    images. We have an OES server that I'd like to use to push & pull images.
    I looked at the Security tab / Upload restrictions in the Server Policy
    and thought I might be able to define exactly where images can be stored
    but haven't made any changes yet. Any ideas on how I can make this work?

    On Wed, 14 Dec 2005 15:39:41 GMT, [email protected] wrote:
    > Is that the only way?
    yes.. the imgserv.nlm does access the harddrive via connection 0... it is
    not able to authenticate..
    and honestly why would you want to pull an image from another server
    causing double amount of traffic..
    you only need to install the imgserv on the other server and reference him
    in your scripts... the old one can do the pxe stuff..
    If you have already compiled drivers or have linux.2 please put them on
    http://forge.novell.com/modules/xfmo...ect/?zfdimgdrv
    Marcus Breiden
    If you are asked to email me information please change -- to - in my e-mail
    address.
    The content of this mail is my private and personal opinion.
    http://www.edu-magic.net

  • How to retrieve deleted images from adobe photoshop album edition 3.0?

    PLS HELP...... :(
    I was connecting my Handphone to PC,trying to retrieve some pictures over..adobe photoshop album edition 3.0 start up automatically..and all the images were ticked. I unticked all..and ticked the 4 images that I want.But i changed my mind & decided not to do it..so i clicked the {X} at the top left corner to close it. it prompt me that 'changes will be lost..(dun remember..)' so i say 'yes'..and my images are gone.. how do i retrieve? PLS advise me!!!! thks

    Hi,
    I could follow you till the message "changes will be lost..." I have seen this message too. However, my images did not get deleted from the device after that. In case you are sure that you did not delete the images accidently, you can report this as a bug to Adobe. Just follow the link below:
    http://www.adobe.com/misc/bugreport.html
    ~Vibha~

  • How can we load images from database to macromedia flash?

    Dear All,
    Actually I'm creating a intractive CD with images(Catalogue)
    loaded in access db. I don't want every user to install the program
    into his pc. When he/she inserts cd it should play and display
    images by category wise (9 pictures at one time). is there flash or
    vb code to acheive this in flash or any flash sample projects
    highly appreciated.
    Thanks a lot

    Hello
    You should look into the option of Retraction from BW to ECC. You may find a lot of docs on the same. Refer the below link for the same
    https://scn.sap.com/thread/1008067
    http://www.sdn.sap.com/irj/scn/go/portal/prtroot/docs/library/uuid/90cd1106-21b4-2d10-0695-9b1e076191eb?QuickLink=index&overridelayout=true
    Regards
    Gajesh

  • How to load a image from database to image item in oracle 10 g form

    I have stored some images in the Database Table with BLOB datatype. Now I need to load that image in the non database image item. Please advise. Thanks.

    You need to have a print server installed to generate the pdf. Either use BI Publisher and it's desktop development tool or use FOP/Cocoon.. Adding an image with them is a little more involved..
    Thank you,
    Tony Miller
    Webster, TX
    While it is true that technology waits for no man; stupidity will always stop to take on new passengers.

  • How to retrieve an image from LDAP

    Hi!
    I have a PL/SQL function which is searching for users using the DBMS_LDAP api's. I can get all the values for all the atributes, but not the attribute called "jpegphoto". I want to know how to get that attribute value for a given session, a given entry, and then how to write the htp.p(); code to display it on my portal page.
    Thank you
    /Marie

    Hello Marie,
    I think you need to ask this question in the OID forum.
    We can help you with PL/SQL Portlet development; but this question is really about the LDAP PL API.
    The URL for OID forum is Identity Manager
    Regards
    Tugdual.

  • How to retrieve the data from database table to the screens

    Hi all,
    I have created a transaction to save the costing details..but if the material code already exists then it should get the header and details of that material code onto the table cotrol of the screen..i'm getiing them into my itab but only the last record of that is visible for n times as there are n records...can anyone help me in this?

    Dear anil ,
      Please give condtion in u r code on line item wise so its taking all records correctly.
    Regards ,
    Nikhil narkhede.

  • How to place an image in database and how to retrieve and display it in the front end

    how to place an image in database and how to retrieve and display it in the front end
    and to place an image in database and retrieve the image from database using xml
    please,help me out.

    Create a table with a Long RAW Datatype column for storing the Image Column Data.
    Create the form based on the table , which by defaults the column with LONG RAW atatype to a Image Item.
    You can use Forms Built in function READ_IMAGE_FILE to read a Image file stored on the file system in to the image item.
    A save on the form saves the image in the Image item in the long raw column.

  • Retrieving image from database in form 6i

    hello all
    i'm working on form 6i...
    i have uploded images into the database of customers in my application using READ_IMAGE_FILE.. IT IS FINE...
    But when i am trying retrieves records into the form.... i'm getting all the data except image... Image field is showing empty..
    How can i get image from database to form
    can u plz help me.....
    thanks

    What data type you used for storing image in database. If it is long raw, then you can place an image item within your data block on form and associate it with the column name. This should populate the image by itself.
    Below para is from Forms Help.
    Image items can be populated in the following ways:
    +1. a fetch from a LONG RAW database column+
    An image item in a data block is populated automatically when the end user or the application executes a query in the block.  When a fetched image is modified or replaced, Form Builder marks that record as Changed, and the next commit operation saves the new image to the corresponding LONG RAW column in the database.
    Note:  You cannot write a SELECT statement to select a LONG RAW value INTO an image item.
    +2. executing the READ_IMAGE_FILE built-in to read an image from the file system+
    +(To dynamically write an image from an image item out to a file, use the built-in procedure WRITE_IMAGE_FILE.)+

  • Showing image from database

    Hi,
    can anyone tell/give me an example/tutorial of how to retrieve the image from the database into forms? so i have a table names EMPLOYEES for example, and i added a clob type column, named "photo". in forms, when i show the informations for each person, i wanna already retrieve the image, somehow. how can i do this? a small example i think will be persuasive :)
    Thanks!
    Regards

    <p>To populate the Image Item you have to use the Webutil Client_Read_Image_File() built-in.</p>
    Francois

  • Retriving an Image From Database

    Hi friends i tried to retrieve an image from database and get some sample code from one website and try to run. But an error will be displayed please help me..... this is the code............
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    import java.io.*;
    import java.sql.*;
    class GetBlob {
    FileOutputStream image;
    Connection con = null;
    PreparedStatement pstmt = null;
    Statement stmt= null;
    ResultSet res = null;
    StringBuffer query=null;
    String driverName = "sun.jdbc.odbc.JdbcOdbcDriver";
    String url = "jdbc:odbc:image";;
    public GetBlob(){
    try{
    Class.forName(driverName);
    con = DriverManager.getConnection(url);
    stmt=con.createStatement();
    ResultSet rs=stmt.executeQuery("SELECT * FROM save_image where id="+"1"+"");
    if (rs.next()) {
    System.out.println(rs.getString(2));
    Blob test=rs.getBlob("image");
    InputStream x=test.getBinaryStream();
    int size=x.available();
    OutputStream out=new FileOutputStream("C:\\anu.jpg");
    byte b[]= new byte[size];
    x.read(b);
    out.write(b);
    catch(Exception e){
    System.out.println("Exception :"+e);
    finally{
    try{
    stmt.close();
    con.close();
    catch(Exception e){
    System.out.println(e);
    public static void main(String args[]) throws IOException{
    GetBlob blob = new GetBlob();
    The error is
    java.lang.UnsupportedOperationException
    please help me...

    Use a real database and a real driver. MS Access and ODBC bridge aren't.

Maybe you are looking for

  • EBS 12.1.1 Windows x86 Rapid Install Errors

    By this point, I am CONVINCED that R12.1.1 is broken for windows x86, in the form that it is delivered at edelivery. I have tried installing it on 2k3 and XP all with the exact same errors. I have also tried the latest rapid install/StartCD version 1

  • Part of page is blurry on Firefox for Android

    Sometimes lower part of the page is blurry on Firefox for Android E.g. https://www.dropbox.com/s/y64ml6eaw5u9xbu/Screenshot_2014-11-17-07-45-19.png?dl=0

  • Load Data from SQL Server to Oracle 10g using Sql*loader utility

    I am trying to lod data from sql server 2005 to oracle 10g. What is the best way to do it? Can sql*loader utility do it? what is the difference of using sql*loader utility and migration tool fom sql developer ? Thanks Edited by: user11313758 on Sep 3

  • Applying  new modules by patch 3180164 question

    Hi, I have 11.5.8 on Windows 2000. I am going to upgrade to the 10.2 and installing patch 3180164 (UPDATE APPLPROD.TXT TO ADD NEW PRODUCTS FOR 11.5.10 MAINTENANCE PACK ) Patch was installed . But after applying this patch it needs: ...Once this patch

  • RESTORING BACKUP FROM Z10 TO Q10 AND OUTLOOK ISSUE!

    Hello Everyone!                              just yesterday I got new blackberry q10 and now its been 8 hours am searching and trying to restore my z10 backup to q10 and am getting error says (incompatible device restore) please need help and I wante