Retrieving Images from a Database

Full Source Code

Image Database SQL

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

TestImage.aspx

<html>
<head><title>View Image from the database</title></head>
<body bgcolor=#FFFFFF>
  Here is the image, viewed from a database:<br />
  <img src="viewimage.aspx?img=1" border=1>
</body>
</html>

ViewImage.aspx

<%@ Page language="c#" Src="ViewImage.aspx.cs" Inherits="DBImages.ViewImage" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<html>
<head></head>
<body>
  <form id="ViewImage" method="post" runat="server"></form>
</body>
</html>

ViewImage.aspx.cs (CodeBehind file)

using System;
using System.Collections;
using System.Configuration;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
namespace DBImages
{
    /// <summary>
    /// Summary description for ViewImage.
    /// </summary>
    public class ViewImage : System.Web.UI.Page
    {
        public ViewImage() { }
        private void Page_Load(object sender, System.EventArgs e)
        {
            //get the image id from the url
            string ImageId = Request.QueryString["img"];
            //build our query statement
            string sqlText = "SELECT img_data, img_contenttype FROM Image WHERE img_pk = " + ImageId;
            SqlConnection connection = new SqlConnection( ConfigurationSettings.AppSettings["DSN"].ToString() );
            SqlCommand command = new SqlCommand( sqlText, connection);
            //open the database and get a datareader
            connection.Open();
            SqlDataReader dr = command.ExecuteReader();
            if ( dr.Read()) //yup we found our image
            {
                Response.ContentType = dr["img_contenttype"].ToString();
                Response.BinaryWrite( (byte[]) dr["img_data"] );
            }
            connection.Close();
        }
    }
}


You might also like...

Comments

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Most software today is very much like an Egyptian pyramid with millions of bricks piled on top of each other, with no structural integrity, but just done by brute force and thousands of slaves” - Alan Kay