Library tutorials & articles

Retrieving Images from a Database

Introduction

In the first part of our article, we uploaded a file and stored it in our database. Now, we are going to stream binary data out of a database and to a browser client.

Refresher - Table Structure

Lets quickly refresh ourselves with the table structure we are using for storing images.

CREATE TABLE [dbo].[image] (
  [img_pk] [int] IDENTITY (1, 1) NOT NULL ,
  [img_name] [varchar] (50) NULL ,
  [img_data] [image] NULL ,
  [img_contenttype] [varchar] (50) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO

ALTER TABLE [dbo].[image] WITH NOCHECK ADD
CONSTRAINT [PK_image] PRIMARY KEY NONCLUSTERED
(
  [img_pk]
) ON [PRIMARY]
GO

We have 4 columns in our sql server:

img_pk - our Identity primary key.
img_name - the friendly name we are using for our image
img_data - the binary data field we are storing our image in.
img_contenttype - the Mime type of our image, for example: image/gif

Comments

  1. 10 May 2009 at 04:01

    I ask please, do not have the source code of image retrieval based on histogram with php language?. If I send to my email address-wanto03@gmail.com. thanks before ..... please confirmation to my email

  2. 20 Oct 2008 at 15:35
    I made a video showing how to do this a while back. Hope it helps. http://tech.kruelintent.com/player.aspx?vid=8 Thanks Tom.
  3. 20 Oct 2008 at 12:40
    There is a free out-of-the-box control that does this with less effort http://www.sharppieces.com/demo/databaseimage.aspx .
  4. 18 Apr 2007 at 06:58

    I am Facing the sam e problem, i am able to store an image into a database as image type but fetching from database in displaying it on a web page is not working.

    Fetching from the database is working fine it is not dispalying on a web page.

    can any body help me out from this problem.

    thanks

    Manoj

    Email me at :  manoj.it01@gmail.com

     

  5. 14 Dec 2005 at 21:13

    Whar is Bind?  I've only seen DataBinder.Eval used here and your examp,le causes a Compilation Error.

  6. 25 Nov 2005 at 17:43

    I've been struggling to get an image to view on my webpage.  I had to make a few changes but no way would it work for me.  I ended up coping and pasting everything, ran into the error at this point : SqlDataReader dr = command.ExecuteReader();  which I thought there was a problem in doing a search based on an index number being an int value and not string.  I made the changes and the error went away but no image came out.  


    any help would be greatly appreciated.


    Judy

  7. 15 Nov 2005 at 21:20

    Hi there! Try this „quite” simple fix. Thanks Dave, you helped a lot with this images mystery…


           <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True"
               AutoGenerateColumns="False" DataKeyNames="imgpk" DataSourceID="ImagesSqlDataSource" Width="627px">
               <Columns>
                   <asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
                   <asp:BoundField DataField="img
    pk" HeaderText="imgpk" InsertVisible="False" ReadOnly="True"
                       SortExpression="img
    pk" />
                   <asp:BoundField DataField="imgname" HeaderText="imgname" SortExpression="imgname" />
                   <asp:BoundField DataField="img
    contenttype" HeaderText="imgcontenttype" SortExpression="imgcontenttype" />
                   <asp:TemplateField HeaderText="imgdata" SortExpression="imgdata">
                       <ItemTemplate>
                           <asp:Image ID="Image1" runat="server" ImageUrl='<%# Bind("img_pk", "ViewImage.aspx?img={0:d}") %>'></asp:Image>
                       </ItemTemplate>
                       <EditItemTemplate>
                            <asp:TextBox ID="TextBox1" runat="server" Text="Sorry, it can not be edited"></asp:TextBox>
                       </EditItemTemplate>
                   </asp:TemplateField>
               </Columns>
           </asp:GridView>





  8. 22 Feb 2005 at 01:49

    hey guys i have the exact same problem as ye have and im just wondering if ye managed to find a solution
    thanks in advance
    tadhg88

  9. 07 Jul 2004 at 04:14

    Hi, did you find a way to make it work they way you wanted?
    I am looking for a way to put it inside a controll as well.

  10. 29 Apr 2004 at 12:04

    How do you deal with Netscape 4 and other browsers that don't like showing images with .aspx extensions?  Is there a way to let these browsers know that that the content is infact a JPG?  I get this message:




    Opening:
    image.aspx using netscape.exe.


    When you download a file from the network, you should be aware of security considerations.


    A file that contains malicious programming instructions could damage or otherwise compromise the contents of your computer.


    You should only use files obtained from sites that you trust.


    What do you want to do with this file?
    Open it
    Save it to disk




  11. 18 Mar 2004 at 15:05

    Hi
    I have a program code in java which is able to retrive and store information in text in a Access database but need the program to be able to do same for Images. Please can anyone help.


    Code Below


    import java.awt.image.;
    import java.awt.
    ;
    import java.sql.;
    import java.util.
    ;
    import javax.swing.*;


    public class Histogram extends JFrame {


       //JDBc driver name and database URL
       static final String driver= "sun.jdbc.odbc.JdbcOdbcDriver";
       static final String url="jdbcdbc:Histogram Database_1";


       //declare Connection and Statement for accessing and querying database
       private Connection connection;
       private Statement statement;


       //Constructor connects to database, quries database, processes
       //results and display results in window
       public Histogram()
       {
           super("Picture Table of Histogram Database_1");


       //connect to database Histogram and query database
       try{
           //load database driver class
           Class.forName(driver);


           //establish connection to database
           connection = DriverManager.getConnection(url);


           //create Statement for querying database
           statement = connection.createStatement();


           //query database
           ResultSet resultSet =
           statement.executeQuery("SELECT Filename FROM PictureTable");
    /////////////$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
    //String CurrentFile = NULL;
    //Image image1.open(CurrentFile);
    //CurrentFile = statement.executeQuery("SELECT Filename FROM PictureTable WHERE PictureID=1");


    ////////////$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
           //process query result
           StringBuffer results = new StringBuffer();
           ResultSetMetaData metaData = resultSet.getMetaData();
           int numberOfColumns = metaData.getColumnCount();



           for(int i = 1; i <=numberOfColumns; i++ )
               results.append( metaData.getColumnName(i) + "\t");


           results.append("\n");



           while( resultSet.next()){
               
               for(int i = 1; i <=numberOfColumns; i++)
                   results.append( resultSet.getObject(i) + "\t");


               results.append("\n");
           }


           //set up GUI and display window
           JTextArea textArea = new JTextArea( results.toString() );
           Container container = getContentPane();


           container.add( new JScrollPane( textArea ) );
           
           setSize(300, 100 );
           setVisible(true);


           }


           //detect problem interacting with the database
           catch ( SQLException sqlException ) {
               JOptionPane.showMessageDialog ( null, sqlException.getMessage(),
               "Database Error", JOptionPane.ERROR_MESSAGE );


           System.exit(1);
           }


           //detect problem loading database driver
           catch ( ClassNotFoundException classNotFound ){
               JOptionPane.showMessageDialog ( null, classNotFound.getMessage(),
               "Driver Not Found", JOptionPane.ERROR_MESSAGE );


               System.exit(1);
           }


               //ensure statement and connection are closed properly
           finally{
               try{
                   statement.close();
                   connection.close();
               }


               //handle exception closing statement and connection
               catch ( SQLException sqlException ) {
                   JOptionPane.showMessageDialog( null, sqlException.getMessage(), "Database Error",
                   JOptionPane.ERROR_MESSAGE );


               System.exit(1);
               }
           }
       }//end Histogram Database_1


       //Lunch the application


       public static void main( String args[] )
       {
           //error found here
           Histogram window = new Histogram();
           window.setDefaultCloseOperation( JFrame.EXITONCLOSE);
       }


       }//end class Histogram Database_1
       

  12. 29 Feb 2004 at 04:26

    Yes, useful as far as it goes, but I would have hoped for:


    a. more information on contentypes


    b. a more complete discussion of the output options, for example displaying it in an image control, resizing it, etc.


    Perhaps a part II?


    John B

  13. 21 Jan 2004 at 02:31

    Hi Dave
    I was going thru your article on uploading and retreiving image from database. It was really good. My requirement is slightly different. When i retreive the image, i would like to display the image on the Image control in asp.net. How do i do that.
    Regards
    Ajay.

  14. 01 Jan 1999 at 00:00

    This thread is for discussions of Retrieving Images from a Database.

Leave a comment

Sign in or Join us (it's free).

Dave Wanta

Related podcasts

Events coming up

  • Mar 15

    DevWeek 2010

    London, United Kingdom

    DevWeek is Europe’s leading independent conference for software developers, database professionals and IT architects, and features expert speakers on a wide range of topics, including .NET 4.0, Silverlight 3, WCF 4, Visual Studio 2010, REST, Windows Workflow 4, Thread Synchronization, ASP.NET 4.0, SQL Server 2008 R2, LINQ, Unit Testing, CLR & C# 4.0, .NET Patterns, WPF 4, F#, Windows Azure, ADO.NET, Entity Framework, Debugging, T-SQL Tips & Tricks, and more.

Want to stay in touch with what's going on? Follow us on twitter!