Place Ads here

Wednesday, February 15, 2012

Storing and Retrieving Image from Database in C# Asp.Net




Storing and Retrieving Image from Database
Write Below code in Default Page


using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;


using System.Data.SqlClient;


public partial class _Default : System.Web.UI.Page 
{
    SqlConnection connection = new SqlConnection("data source=.; Initial catalog=LoadPhoto;integrated security=sspi;");




    protected void Page_Load(object sender, EventArgs e)
    {


    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        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 = ConfigurationManager.ConnectionStrings["EmployeeConnString"].ConnectionString;
            //connection = new SqlConnection(conn);


            connection.Open();
            string sql = "INSERT INTO EmpDetails(empname,empimg) 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);


            Image1.ImageUrl = "~/ShowImage.ashx?id=" + id;
        }
        catch
        {
            lblResult.Text = "Photo Size should be less than 20 KB";
        }
        finally
        {
            connection.Close();
        }
    }
}




////////////////////////////////////////////////////////////////////////////////////////////////


Write the below code in  ShowImage.ashx file



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


using System;

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

public class ShowImage : IHttpHandler

{


    SqlConnection connection = new SqlConnection("data source=.; Initial catalog=LoadPhoto;integrated security=sspi;");
    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);
       }       
       //context.Response.BinaryWrite(buffer);
    }

    public Stream ShowEmpImage(int empno)

    {
 //string conn = ConfigurationManager.ConnectionStrings     ["EmployeeConnString"].ConnectionString;
        //SqlConnection connection = new SqlConnection(conn);
        
        
        string sql = "SELECT empimg 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();
        }
    }

    public bool IsReusable

    {
        get
        {
            return false;
        }
    }


}



8 comments:

  1. want to display image by matching the text box text into table content and getting primary key then matching that primary key into the image name in if loop..
    it not getting work.. please help me.. its for my final year project.. i have to submit in 10 daysss
    My Email id venmukilanmukilan@gmail.com
    Thank you

    ReplyDelete
  2. Thanks for sharing this. We really want to find a good website design company. Our business could really use one. What would you suggest?
    Asp.net development company Delhi

    ReplyDelete
    Replies
    1. Thanks for the appreciation.For Web Design Company You can go for or
      http://in.webuy.com/contact/
      Mumbai
      or
      http://www.webele.in/
      Maphe Vashi.

      Delete
    2. You can give my reference Mr Amul V Wayangankar

      Delete
  3. i want only retriving of images from data base so pls send some logic plsssss help me
    MY MAIL:barnalarajesh@gmail.com

    ReplyDelete
  4. Hi,Nice asp.net code for storing and retrieving images from database in c#

    Theosoft

    ReplyDelete
  5. Hi, nice code for Storing and Retrieving Image from Database in C# Asp.Net

    Theosoft

    ReplyDelete
  6. I want a Free Sample Project with SQL Database

    Email Me at lisagosh82@gmail.com

    ReplyDelete