Click here to Skip to main content
Click here to Skip to main content

Tagged as

Go to top

storing and retriving images from database using ASP.NET

, 1 Dec 2011
Rate this:
Please Sign up or sign in to vote.
Code for storing and retrieving images from database using ASP.NET.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
public partial class Default2 : System.Web.UI.Page
    protected void Page_Load(object sender, EventArgs e)
        int id = Convert.ToInt32(Request.QueryString["imagId"]);
        if (id > 0)
            //connect to the db
            SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=F:\Examples\ImageExamples\Images1\ImageStoringAndRetrivingUsingImageConrtol\App_Data\Database1.mdf;Integrated Security=True;User Instance=True");
            //sql command to select the image with id of 1
            SqlCommand cmd = new SqlCommand("SELECT * FROM Images WHERE ImgId=@ImgId", conn);
            cmd.CommandType = CommandType.Text;
            //select the image with ImgId of 1
            cmd.Parameters.AddWithValue("@ImgId", id);
            using (conn)
                //open the connection
                //send the sql query to select the image and store the results in a sqldatareader
                SqlDataReader rdr = cmd.ExecuteReader();
                //read the data
                if (rdr.Read())
                    //store the image binary data in a byte array
                    Byte[] imgData = (byte[])rdr["ImgBin"];
                    //setup the image type to be displayed
                    Response.ContentType = (rdr["ImgType"].ToString());
                    //output the image to the page
                    Response.OutputStream.Write(imgData, 0, imgData.Length);


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


About the Author

No Biography provided

Comments and Discussions

GeneralBut i am using ms access as a database PinmemberJanardan Pandey23-Jan-12 23:32 
GeneralRe: Actually i don't know much about ms access database but i wi... PinmemberD.rajasekharreddy31-Jan-12 3:13 
GeneralReason for my vote of 1 This has been seen hundreds of times... Pinmembermdarco1-Dec-11 21:28 

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

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

| Advertise | Privacy | Mobile
Web04 | 2.8.140916.1 | Last Updated 1 Dec 2011
Article Copyright 2011 by D.rajasekharreddy
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid