Storing Images in SQL Server

Last Updated: 2002

Topics

Saving Images to SQL Server
using System;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;

namespace ConsoleApplication1
{
    /// <summary>
    /// Summary description for Class1.
    /// </summary>
    class Class1 {
	static void Main() {
	   SqlConnection oConnection = new SqlConnection("server=(local);database=persnl;Trusted_Connection=yes");
	   SqlCommand oCommand = new SqlCommand("update people set photograph = @photograph where employee_number=@employee_number", oConnection);
		SqlParameter oP1 = new SqlParameter("@photograph", SqlDbType.Image);
		SqlParameter oP2 = new SqlParameter("@employee_number", SqlDbType.Char, 12);
 
		FileStream oFS = new FileStream(@"c:\screen.bmp", FileMode.Open, FileAccess.Read);
		BinaryReader oBR = new BinaryReader(oFS);
		byte[] pByte= new byte[oFS.Length];
		oBR.Read(pByte, 0, (int) oFS.Length);
		oBR.Close();
 
		oP1.Value= pByte;			
		oP2.Value="000001";
		oCommand.Parameters.Add(oP1);
		oCommand.Parameters.Add(oP2);
 
		oConnection.Open();
		oCommand.ExecuteNonQuery();
		oCommand.Dispose();
		oConnection.Close();
	     }
	 }
     }

Back to Topic List 

 

Returning Images From SQL Server to a Web Client

The following aspx page returns an image instead of a HTML page. To use it another page would reference it from a <Image> or <asp:Image> tag. For example:

<asp:Image id="myImage" runat=server ImageUrl="photo.aspx?Employee=00001" />

photo.aspx would therefore look like this:

<%@language=c# %>
<%@Import Namespace="System.Data" %>
<%@Import Namespace="System.Data.SqlClient" %>
<%
string strEmployee = Request.QueryString["Employee"];
SqlConnection oConnection = new SqlConnection("server=(local);database=persnl;Trusted_Connection=yes");
SqlCommand oCommand = new SqlCommand(
    "select photograph from people where employee_number = '" +
    strEmployee + "'", oConnection);

oConnection.Open();
SqlDataReader oReader = oCommand.ExecuteReader();
if(!oReader.Read()) {
    Response.Write("No data!");
} else {
    Response.ContentType = "image/bmp";
    int iSize = (int) oReader.GetBytes(0, 0, null, 0, 0);
    byte[] pBuffer = new byte[iSize];
    oReader.GetBytes(0, 0, pBuffer, 0, iSize);
    Response.BinaryWrite(pBuffer);
}

oReader.Close();
oCommand.Dispose();
oConnection.Close();
%>
 

Note that there is no "codebehind" or ".cs" file.

Note #2: Since writing this code I've come across the tutorial for creating custom HTTP handlers which, had I known of them at the time, been the method of choice for implementing the above. Custom HTTP handlers merely require the implementation of ISimpleHandler and a line in web.config.

Back to Topic List