Save and Retrieve Image from Database


asp.net save and retrieve image from database

In this articles i'm going to explain how to Save and Retrieve Image From Database and display in div container dynamically in Asp.net by using C# Coding. In above image you see i have used 4 controllers i.e 2 textbox, 1 fileuploader and 1 button control,

  1. TextBox is used to display ImageID is nothing but a Auto Generate Number,
  2. TextBox is used to enter Image Name
  3. Fileuploader control is used to choose Image from your device

Create Image Database

save image and retrieve image from database in asp.net

Create CSS Code :


 <style type="text/css">
     #tableimg
     {
         border-collapse:collapse;
         width:600px;         
     }
     #tableimg th
     {
         padding:5px 10px 5px 10px;
         background-color:#222;
         color:#fff;
         border:1px solid #222;
     }
     .row1, .row2, .ImageBox
     {
         border:1px solid #222;
     }
     .row1, .row2
     {
         padding:3px;
         text-align:left;
     }
     .row2
     {
         width:350px;
     }
     .txt
     {
         width:300px;
     }
     .txt, .ImageBox, ImageBox:hover
     {
         padding:5px;
     }
     .ImageBox, ImageBox:hover
     {
         width:150px;
         height:150px;
         margin:5px;
     }
     .ImageBox:hover
     {
         border:1px solid #e4e4e4;
         background-color:#222;
     }
   </style>

Create HTML 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></title>
   <style>
   
    ---------- CSS Code Here----------
    
   </style>
</head>
<body>
    <form id="form1" runat="server">
    <div style="margin:30px 40px 0px 20px;">
      <table id="tableimg">
       <tr>
        <th colspan="2">Save and Retrieve Image from Database</th>
       </tr>
       <tr>
        <td class="row1">
         Enter Image ID :
        </td>
        <td class="row2">
         <asp:TextBox ID="txtimageID" runat="server" CssClass="txt" BackColor="Silver" 
                ReadOnly="True"></asp:TextBox>
        </td>
       </tr>
       <tr>
        <td class="row1">
         Enter Image Name :
        </td>
        <td class="row2">
         <asp:TextBox ID="txtimagename" runat="server" CssClass="txt"></asp:TextBox>
        </td>
       </tr>
       <tr>
        <td class="row1">
         Choose Image :
        </td>
        <td class="row2">
         <asp:FileUpload ID="FileUpload1" runat="server" CssClass="txt" />
        </td>
       </tr>
       <tr>
        <td colspan="2">
         <asp:Button ID="btn_saveimage" runat="server" Text="Image Save" 
                onclick="btn_saveimage_Click" />
        </td>
       </tr>
       </table>
    </div>
    <br />
    <div id="divimg" runat="server"></div>
    </form>
</body>
</html>


C# Coding : Namespace


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

C# Coding : Image Auto Generate ID :


GetImageID method is used to execute SQL Query i.e Select ISNULL(MAX(imgid),10000) from image this select query means whenever we execute this query its retrieve MAX(imgid) value from imgid column, if imgid column is null then it will return Null values instead of null values we can assign some value. ISNULL(MAX(imgid),10000) is used to return 10000 if imgid column is NULL.

private int GetImageID()
    {
        try
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("select Isnull(MAX(imgid),10000) from image", con);
            int i = Convert.ToInt32(cmd.ExecuteScalar());
            i++;
            return i;
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            con.Close();
        }
    }

C# Coding : Display Image's

DisplayImage() method is used to retrieve all images from Database and display image's through dynamically created Image Control in webpage.

private void DisplayImage()
    {
        SqlDataAdapter da = new SqlDataAdapter("Select * from Image", con);
        DataSet ds=new DataSet();
        da.Fill(ds);
        if(ds.Tables[0].Rows.Count>0)
        {
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                // its required type casting to convert from Dataset type to binary
                byte[] bytes = (byte[])ds.Tables[0].Rows[i]["image"];

                //convert to string
                string strbase64 = Convert.ToBase64String(bytes);

                // this Image Control is creating dynamically and add to divimg which was already declared in html
                Image img = new Image();
                img.ID = i.ToString();
                img.CssClass = "ImageBox";
                img.ImageUrl = "data:Image/png;base64," + strbase64;


                divimg.Controls.Add(img);
            }
            
        }
    }

C# Coding : Page Loading

In Page Load DisplayImage() method is used to retrieve all images and display in dynamically created image control. GetImageID() method is return integer value which is nothing but a ImageID and we are assigning that value to TextBox Image Id (txtimageID).

 protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DisplayImage();
            int ImgID = GetImageID();
            txtimageID.Text = ImgID.ToString();
        }
    }

C# Coding : Image Save Button Click


  protected void btn_saveimage_Click(object sender, EventArgs e)
    {
        try
        {            
            HttpPostedFile postfile = FileUpload1.PostedFile;
            string filename = Path.GetFileName(postfile.FileName);
            string fileExtension = Path.GetExtension(filename);
            int filesize = postfile.ContentLength;
            if (fileExtension.ToLower() == ".jpg" || fileExtension.ToLower() == ".png" || fileExtension.ToLower() == ".gif" || fileExtension.ToLower() == ".bmp")
            {
                Stream imgstream = postfile.InputStream;
                BinaryReader binaryreader = new BinaryReader(imgstream);
                byte[] imgbytes = binaryreader.ReadBytes((int)imgstream.Length);

                //Save Image Data into Database
                con.Open();
                SqlCommand cmd = new SqlCommand("Insert into Image(imgid, imagename, image) values('" + txtimageID.Text + "','" + txtimagename.Text + "',@image)", con);
                cmd.Parameters.AddWithValue("@image", SqlDbType.Binary).Value = imgbytes;
                int i=cmd.ExecuteNonQuery();
                con.Close();
                if (i > 0)
                {
                    DisplayImage();
                    int ImgID = GetImageID();
                    txtimageID.Text = ImgID.ToString();                    
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            con.Close();
        }

    }
Tag : ASP.NET, Image
0 Komentar untuk "Save and Retrieve Image from Database"

Back To Top