hi,
how to save an image into database. ie how to insert an image into database and how to get the image back. i am using the asp.net(C#.net) and mssql server 2000 . so can u tell me the solution.

hi,
step 1:
create a db Employee and Table EmpDetails having Columns Empid(int) set its isidentity to true,EmpImage(Image),EmpName(nchar(20)).

step 2:
create an aspx page

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Save Retrieve Images</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        <asp:Label ID="lblEmpName" runat="server" Text="Employee Name"></asp:Label>
&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:TextBox ID="txtEName" runat="server"></asp:TextBox>
        <br />
        <asp:Label ID="lblImage" runat="server" Text="Employee Image"></asp:Label>
&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:FileUpload ID="imgUpload" runat="server" />
        <br />
        <br />
        <asp:Button ID="btnSubmit" runat="server" onclick="btnSubmit_Click"
            Text="Submit" />
   
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp        <asp:Label ID="lblResult" runat="server" ForeColor="#0066FF"></asp:Label>
    <br />
    <hr />
  
   <asp:Image ID="Image1" style="width:200px" Runat="server" />
 
   
   
    </div>
    </form>
</body>
</html>

step 3:
add below code to insert image and name to database

using System.Data.SqlClient;
//Submit button click event
 protected void btnSubmit_Click(object sender, EventArgs e)
    {
        SqlConnection connection = null;
        try
        {
            FileUpload img = (FileUpload)imgUpload;
            Byte[] imgByte = null;
            if (img.HasFile && img.PostedFile != null)
            {
                //To create a PostedFile
                HttpPostedFile File = imgUpload.PostedFile;
                //Create byte Array with file len
                imgByte = new Byte[File.ContentLength];
                //force the control to load data in array
                File.InputStream.Read(imgByte, 0, File.ContentLength);
            }
            // Insert the employee name and image into db
            string conn = "Data Source=.;Initial Catalog=Employee;integrated Security=true;";
            connection = new SqlConnection(conn);

            connection.Open();
            
            string sql = "INSERT INTO EmpDetails(empname,empimage) VALUES(@enm, @eimg) SELECT @@IDENTITY";
            SqlCommand cmd = new SqlCommand(sql, connection);
            cmd.Parameters.AddWithValue("@enm", txtEName.Text.Trim());
            cmd.Parameters.AddWithValue("@eimg", imgByte);
            int id = Convert.ToInt32(cmd.ExecuteScalar());
            lblResult.Text = String.Format("Employee ID is {0}", id);
//remove the comment of below line when step 4 is done.
// Image1.ImageUrl = "~/Handler.ashx?id=" + id;
        }
        catch
        {
            lblResult.Text = "There was an error";
        }
        finally
        {
            connection.Close();
        }
 
    }

step 4:
In order to display the image on the page, we will create an Http handler. To do so, right click project > Add New Item > Generic Handler > Handler.ashx.

Handler.ashx is

<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Configuration;
using System.Web;
using System.IO;
using System.Data;
using System.Data.SqlClient;

public class Handler : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        Int32 empno;
        if (context.Request.QueryString["id"] != null)
            empno = Convert.ToInt32(context.Request.QueryString["id"]);
        else
            throw new ArgumentException("No parameter specified");

        context.Response.ContentType = "image/jpeg";
        Stream strm = ShowEmpImage(empno);
        byte[] buffer = new byte[4096];
        int byteSeq = strm.Read(buffer, 0, 4096);

        while (byteSeq > 0)
        {
            context.Response.OutputStream.Write(buffer, 0, byteSeq);
            byteSeq = strm.Read(buffer, 0, 4096);
        }       
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }


    public Stream ShowEmpImage(int empno)
    {
        string conn = "Data Source=.;Initial Catalog=Employee;integrated Security=true;";
        SqlConnection connection = new SqlConnection(conn);
        string sql = "SELECT empimage FROM EmpDetails WHERE empid = @ID";
        SqlCommand cmd = new SqlCommand(sql, connection);
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.AddWithValue("@ID", empno);
        connection.Open();
        object img = cmd.ExecuteScalar();
        try
        {
            return new MemoryStream((byte[])img);
        }
        catch
        {
            return null;
        }
        finally
        {
           
            connection.Close();
        }
    }

}

Thanks
Chithra

hi,
thank you very much. It is working perfectly.. when i click on submit butoon it is saved in database but error in handler.aspx . the error is :
" no parameters specified" at the line ( context.Response.ContentType = "image/jpeg"; ). so how to get back the image .

Again, this was covered extensively:
http://www.daniweb.com/forums/thread209172.html

This code will retrieve the image as a byte[] array from the database:

private static byte[] GetImage()
    {
      byte[] result = null;

      const string query = @"Select Top 1 Picture From Picture";
      using (SqlConnection conn = new SqlConnection(BuildSqlNativeConnStr("apex2006sql", "Bugs")))
      {
        conn.Open();
        using (SqlCommand cmd = new SqlCommand(query, conn))
        {
          using (SqlDataReader dr = cmd.ExecuteReader())
          {
            using (DataTable dt = new DataTable())
            {
              dt.Load(dr);
              if (dt.Rows.Count > 0)
              {
                DataRow row = dt.Rows[0];
                if (row["Picture"] != DBNull.Value)
                {
                  try
                  {
                    result = (byte[])row["Picture"];
                  }
                  catch { }
                }
              }
            }
          }
        }
      }
      return result;
    }

As far as sending it down stream:

byte[] picture = GetImage();
          Response.ContentType = "image/bmp";
          Response.BinaryWrite(picture);

Please post the code you have so far and we'll go from there.

Hello sknake sir I didnt get ur code..Can u tell me is it necesarry or not to have handler.aspx ...to get the image from DB..See in mine code below-???


hello mohan sir , I m saving the multiple images & extracting the multiple images..may be this is lenthgy method,but have a look at it-

SQL
COLUMN NAME DATATYPE
id int
image1 image
img_type varchar


Drag the fileUpLoad control on the form,so dat u can choose aby file-
FrmSaveImage.aspx

public partial class _Default : System.Web.UI.Page 
{
    string query;
    SqlConnection conn = new SqlConnection("Data Source=SONIA-B408A4159\\SQLEXPRESS;Initial catalog=sonia;Integrated Security=true");
      
    protected void Button1_Click(object sender, EventArgs e)
    {

        if (FileUpload1.PostedFile.FileName == null
|| FileUpload1.PostedFile.FileName == "")
        {
            lblErrors.Text = "Please Select the file";
                  }
        else
        {
         byte[] myimage = new byte[FileUpload1.PostedFile.ContentLength]; 
HttpPostedFile Image = FileUpload1.PostedFile; 
Image.InputStream.Read(myimage, 0, (int)FileUpload1.PostedFile.ContentLength);

query = "Insert into ImageGalleyNew values(@image1,@imgtype)";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue("@image1", myimage);
cmd.Parameters.AddWithValue("@imgtype", FileUpload1.PostedFile.ContentType);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
        }
            }

FrmGetImage.aspx

Drag the Gridview, with one column images
CODE BEHIND PAGE

public partial class Default2 : System.Web.UI.Page
{
   
    SqlConnection conn = new SqlConnection("Data Source=SONIA-B408A4159\\SQLEXPRESS;Initial catalog=sonia;Integrated Security=true");
   
        protected void Page_Load(object sender, EventArgs e)
    {
        GridView1.DataSource = FetchAllImagesInfo();
        GridView1.DataBind();
        
         }

    public DataTable   FetchAllImagesInfo()
{
    string sql = "Select * from ImageGalleyNew";
  SqlDataAdapter da = new SqlDataAdapter(sql, conn);
  DataTable dt = new DataTable();
   da.Fill(dt);
           return dt;
}

     

    }

SOURCE TAB

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
            <Columns>
                <asp:TemplateField HeaderText="images">
                <itemtemplate>
                    <asp:Image ID="Image1"  Width="50" Height="50"  runat="server" ImageAlign ="Middle" ImageUrl='<%#"GetDBImage.ashx?id=" + Eval("id")  %>' />
                                  </itemtemplate>
                </asp:TemplateField>
                                </Columns>
        </asp:GridView>

Handler.aspx

<%@ WebHandler Language="C#" Class="GetDBImage" %>

using System;
using System.Web;
using System.Data.SqlClient;
using System.Data; 

public class GetDBImage : IHttpHandler {
        public void ProcessRequest (HttpContext context)
        {
            string id = context.Request.QueryString["id"];
        SqlConnection conn = new SqlConnection("Data Source=SONIA-B408A4159\\SQLEXPRESS;Initial catalog=sonia;Integrated Security=true");
        conn.Open();
        string query = "select * from ImageGalleyNew where id = @ImageId";
      SqlCommand  cmd = new SqlCommand(query, conn);
      cmd.Parameters.Add("@ImageId", SqlDbType.Int).Value = context.Request.QueryString["id"];
      cmd.Prepare(); 
     SqlDataReader  dr = cmd.ExecuteReader();
     dr.Read();
    context.Response.ContentType = dr["img_type"].ToString();
     context.Response.BinaryWrite((byte[])dr["image1"]);
     dr.Close();
     conn.Close();
      }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

hi,
Thanks for sending the code. i have one doubt , can we get the one record from database and print that record into data grid. the record contains userid,username and userimage. it should be performed when the button clicks. Thank you very much...

hi ,
Thank you sir, for sending the code and ur suggestions .i have small problem to get the fields along with image. i am getting the image from database but the empid and empname not displayed in respected fields. image only displayed ,remaining fields are not displayed. i am sending the code of it .is it correct or not.. thank you ...

///***** this is the code in button click ***////

SqlConnection MyConnection = new SqlConnection("user id=sa;password=sa;database=school;server=localhost");
        SqlCommand MyCommand = new SqlCommand("SELECT * FROM empdetails WHERE empid='" + tb1.Text + "'", MyConnection);
        MyConnection.Open();
        SqlDataReader MyReader = MyCommand.ExecuteReader();
        if (MyReader.Read())
        {
            tb2.Text = MyReader["empname"].ToString();
            byte[] m_MyImage = (byte[])MyReader["empimage"]; //*** to get image from database
            Response.BinaryWrite(m_MyImage);

****
tb1.text contains the empid.


////**** this is the code in .aspx page

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <br />
        <br />
        &nbsp; &nbsp;
        <table>
            <tr>
                <td style="width: 100px">
                    <asp:Label ID="lbl1" runat="server" Text="Emp ID" Width="98px"></asp:Label></td>
                <td style="width: 100px">
                    <asp:TextBox ID="tb1" runat="server" Width="133px"></asp:TextBox></td>
            </tr>
            <tr>
                <td style="width: 100px">
                    <asp:Label ID="lbl2" runat="server" Text="Emp Name" Width="98px"></asp:Label></td>
                <td style="width: 100px">
                    <asp:TextBox ID="tb2" runat="server" Width="134px"></asp:TextBox></td>
            </tr>
            <tr>
                <td style="width: 100px">
                    <asp:Label ID="lbl3" runat="server" Text="Emp Image" Width="98px"></asp:Label></td>
                <td style="width: 100px">
                    <asp:Image ID="img" runat="server" Height="77px" ImageAlign="Left" Width="92px" /></td>
            </tr>
            <tr>
                <td style="width: 100px">
                </td>
                <td style="width: 100px">
                    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="get" Width="99px" /></td>
            </tr>
        </table>
    
    </div>
    </form>
</body>
</html>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.