How to save image in database Data base design:
Store Image in Grid: To store image in database first we have to open and read the file and convert the file into byte array. For saving to database The C# coding to save image: SqlConnection con = new SqlConnection("Connection string"); con.Open(); SqlCommand oc=new SqlCommand("insert into TableName values(@Image)",con); string path=@"Path\imagename.JPG"; FileStream fs=new FileStream(path,FileMode.Open,FileAccess.Read); BinaryReader br=new BinaryReader(fs); FileInfo fi=new FileInfo(path); byte[] imagedata = br.ReadBytes((int)fi.Length); oc.Parameters.Add("@Image", imagedata); oc.ExecuteNonQuery(); con.Close();
Retrieve image from database using handler.
Code used in Imagehandler.aspx public class Handler1 : IHttpHandler { public void ProcessRequest(HttpContext context) { string imageid = context.Request.QueryString["Image"]; SqlConnection con = new SqlConnection("Connectionstring"); con.Open(); SqlCommand command = new SqlCommand("select Image from ImageExample", con); SqlDataReader dr = command.ExecuteReader(); dr.Read(); context.Response.BinaryWrite((Byte[])dr[0]); con.Close(); context.Response.End(); } public bool IsReusable { get { return false; } } } Code used in aspx page <asp:GridView ID="GridView1" runat="server" Width="500px" AutoGenerateColumns="false"> <Columns> <asp:TemplateField HeaderText="Image"> <ItemTemplate> <asp:Image ID="Image" runat="server" ImageUrl='<%#"ImageHandler.ashx"%>'/> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView>
Code used in Retrieve image using C# SqlConnection con = new SqlConnection("Connnection string"); con.Open(); SqlCommand oc = new SqlCommand("Select * from ImageExample", con); SqlDataAdapter da = new SqlDataAdapter(oc); DataTable dt = new DataTable(); da.Fill(dt); GridView1.DataSource = dt; GridView1.DataBind();
You need to be a premium member to use this feature. To access it, you'll have to upgrade your membership.
Become a sharper developer and jumpstart your career.
$0
$
. 00
monthly
For Basic members:
$20
For Premium members:
$45
For Elite members: