Click here to Skip to main content
15,394,479 members
Articles / Web Development / ASP.NET
Posted 13 Feb 2009


68 bookmarked

C# Save and Load Image from Database

Rate me:
Please Sign up or sign in to vote.
3.57/5 (40 votes)
5 Mar 2009CPOL3 min read
Save images to database and load in aspx page using C#


This article shows you how to upload an image in a C# application, save it in a database and display it in another aspx page.


HTML img tag and Image control in C# always look for an image on the hard disk or some physical location on a server. This article shows how to overcome that by specifying the image source as another aspx file which returns an image.

It may not be feasible to store all the images on the hard disk and index them. It also takes more time to read and write to a hard disk. So, storing the images in database is the way to go if your application uses more images in a dynamic page.

This article shows how to display dynamic images from database, how to convert image to bytearray and how to use generic handlers.

Using the Code

First the uploaded image must be saved in the database.

Image Upload

Upload functionality can be implemented easily by using the Fileupload control and a submit button in the upload page.

<asp:FileUpload runat="server" ID="flImage" />
<asp:Button runat="server" ValidationGroup="Details" ID="btnSubmit" Text="Upload"
    onclick="btnSubmit_Click" />

The selected image from the fileupload control must be stored in the msg table. Let us assume the msg table has two fields:

Table Name: msg

Field NameData TypePrimary KeyNullable

Have the msgid as an autoincrement field if required so that it may not be required to be updated.

On the submit button click event, insert a record in msg table.

The selected image must be converted to a byte array before being inserted into the table.

private byte[] ConvertImageToByteArray(System.Drawing.Image imageToConvert,
                                       System.Drawing.Imaging.ImageFormat formatOfImage)
    byte[] Ret;
        using (MemoryStream ms = new MemoryStream())
            imageToConvert.Save(ms, formatOfImage);
            Ret = ms.ToArray();
    catch (Exception) { throw; }
    return Ret;

On the submit button click event, get the selected image in the Image object by calling...


... and store it in the image object. This image object must be converted to a byte array to be able to store in a blob field. This is done by calling the above ConvertImageToByteArray() function.

Now setup the database connection in the button click event and update the msg table's pic1 field with the bytearray that we got from the ConvertImageToByteArray() function.

//Upload image to database
protected void btnSubmit_Click(object sender, EventArgs e)
    System.Drawing.Image imag = System.Drawing.Image.FromStream(
    System.Data.SqlClient.SqlConnection conn = null;
            conn = new System.Data.SqlClient.SqlConnection(
            System.Data.SqlClient.SqlCommand insertCommand =
                new System.Data.SqlClient.SqlCommand(
                "Insert into [msg] (msgid, pic1) Values (1, @Pic)", conn);
            insertCommand.Parameters.Add("Pic", SqlDbType.Image, 0).Value =
                ConvertImageToByteArray(imag, System.Drawing.Imaging.ImageFormat.Jpeg);
            int queryResult = insertCommand.ExecuteNonQuery();
            if (queryResult == 1)
                lblRes.Text = "msg record Created Successfully";
        catch (Exception ex)
            lblRes.Text = "Error: " + ex.Message;
        if (conn != null)

Generic Handler to Display Image

As we know, the aspx image control looks for a physical location of an Image file in its ImageUrl attribute. The trick is to specify another dedicated handler file which will act as an image. This handler (ImgHandler.ashx) will not have any HTML decoration since we are not displaying this page separately, instead it will act as an image. To do that, its ProcessRequest event must be modified to read the image from the database and return the image as the response.

Calling Response.BinaryWrite() function from the ProcessRequest event will make this ashx handler as an image by the calling aspx page.

public void ProcessRequest (HttpContext context)
        System.Data.SqlClient.SqlDataReader rdr = null;
        System.Data.SqlClient.SqlConnection conn = null;
        System.Data.SqlClient.SqlCommand selcmd = null;
          conn = new System.Data.SqlClient.SqlConnection
          selcmd = new System.Data.SqlClient.SqlCommand
		("select pic1 from msg where msgid=" + 
		context.Request.QueryString["imgid"], conn);
          rdr = selcmd.ExecuteReader();
          while (rdr.Read())
            context.Response.ContentType = "image/jpg";
          if (rdr != null)
          if (conn != null)

In the above code, notice that the ProcessRequest event opens the database and loads the image with the image id matching the image id sent from the request query string.

This code only saves and retrieves images in JPG format. Although other image formats like GIF, PNG, BMP, etc. will work with the same code, the image quality will not be maintained if all other image formats are read as JPG formats. This code must be updated to handle different image formats while writing to database and setting the content type in the response.

Display the Image

Now this can be accessed from any aspx page by setting the ImageUrl to the above handler.

<asp:Image ID="picone" ImageUrl="ImgHandler.ashx?imgid=1" runat="server" />

imgid is sent as a querystring to ImgHandler.ashx in order to fetch the right image from the database and display it.

Points of Interest

Image control in C# expects ImageUrl which is a physical image in the server. This article shows the workaround of making an ashx handler behave like a physical image. It also presents all the related code behind saving and retrieving image to and from database. This article shows database access in plain SQL in code for quick understanding. These SQL statements must be protected to prevent from SQL injection by hackers.

Happy coding!


  • 13th February, 2009: Initial post


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Software Developer (Senior)
United States United States
Founder of, a multilingual classifieds portal for indian cities. Working in open systems development since 1997 in Delphi, Java, C++ and C#.

Comments and Discussions

GeneralMy vote of 1 Pin
Member 1069738610-Jan-18 1:16
MemberMember 1069738610-Jan-18 1:16 
QuestionStoring image in a variable and passing it through ajax webservice to push into Oracle database Pin
Member 127517046-Dec-17 0:22
MemberMember 127517046-Dec-17 0:22 
QuestionOptional Pin
Shoaib Safi3-Jan-15 21:04
MemberShoaib Safi3-Jan-15 21:04 
QuestionPlease Help!!! Pin
akshaychawla17-Oct-13 22:16
Memberakshaychawla17-Oct-13 22:16 
Questionhow to insert an image to database in c#.. Pin
Parth3227-Aug-13 19:47
MemberParth3227-Aug-13 19:47 
QuestionSave Image through path into database Pin
NazarHussain6-Nov-12 21:41
MemberNazarHussain6-Nov-12 21:41 
AnswerRe: Save Image through path into database Pin
GiXxXmO3-Dec-12 9:23
MemberGiXxXmO3-Dec-12 9:23 
GeneralRe: Save Image through path into database Pin
NazarHussain8-Jan-13 18:45
MemberNazarHussain8-Jan-13 18:45 
GeneralMy vote of 5 Pin
Gianpiero Caretti3-Nov-12 15:58
MemberGianpiero Caretti3-Nov-12 15:58 
Questionhelp Pin
dr.m-rostami19-Jun-12 20:12
Memberdr.m-rostami19-Jun-12 20:12 
GeneralMy vote of 1 Pin
Mico Perez28-Nov-11 4:07
MemberMico Perez28-Nov-11 4:07 
GeneralRe: My vote of 1 Pin
nishant barsainyan18-Mar-12 23:20
Membernishant barsainyan18-Mar-12 23:20 
Questionnot working at my pc Pin
Vipul shisodia24-Oct-11 16:23
MemberVipul shisodia24-Oct-11 16:23 
GeneralGreat Piece of information After Searching Everywhere for Database to Web Page Images Pin
Joseph Dixon30-Mar-11 3:53
MemberJoseph Dixon30-Mar-11 3:53 
GeneralMy vote of 1 Pin
chirag848-Mar-10 0:00
Memberchirag848-Mar-10 0:00 
GeneralThank you for posting the code Pin
defwebserver14-Feb-09 12:30
Memberdefwebserver14-Feb-09 12:30 
GeneralRe: Thank you for posting the code Pin
senthilvasan19-Feb-09 8:43
Membersenthilvasan19-Feb-09 8:43 
GeneralUse an .ashx handler instead Pin
Allan Eagle14-Feb-09 11:03
MemberAllan Eagle14-Feb-09 11:03 
GeneralRe: Use an .ashx handler instead Pin
senthilvasan19-Feb-09 8:44
Membersenthilvasan19-Feb-09 8:44 
GeneralMy vote of 1 Pin
zlezj14-Feb-09 2:13
Memberzlezj14-Feb-09 2:13 
GeneralRe: My vote of 1 Pin
glen.stevens22-Dec-09 0:10
Memberglen.stevens22-Dec-09 0:10 
Questionwhat you are trying to explain? Pin
MussaratAziz14-Feb-09 1:31
MemberMussaratAziz14-Feb-09 1:31 
AnswerRe: what you are trying to explain? Pin
Velio Ivanov15-Feb-09 2:16
MemberVelio Ivanov15-Feb-09 2:16 
GeneralRe: what you are trying to explain? Pin
senthilvasan19-Feb-09 8:57
Membersenthilvasan19-Feb-09 8:57 
RantRe: what you are trying to explain? Pin
Xequence22-Jul-09 8:26
MemberXequence22-Jul-09 8:26 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.