Save (Insert) Binary Image to database using Image Control in ASP.Net

Last Reply 7 months ago By pandeyism

Posted 7 months ago

Dear Team,

we have Displaying image from SQL database using image but while updating how to store Image Value to database with same Value.

Image Retrive & Save Code

// ImageRetriveCode
if (ds.Tables[0].Rows[0]["Image_Data"] != DBNull.Value)
{
    string imageUrl = "data:image/jpg;base64," + Convert.ToBase64String((byte[])ds.Tables[0].Rows[0]["Image_Data"]);
    imgDoctor.ImageUrl = imageUrl;
}

//ImageSaveCode
if (fileExtension.ToLower() == ".jpg" || fileExtension.ToLower() == ".bmp" || fileExtension.ToLower() == ".gif" || fileExtension.ToLower() == ".png")
{
    Stream stream = postedFile.InputStream;
    BinaryReader binaryReader = new BinaryReader(stream);
    byte[] bytes = binaryReader.ReadBytes((int)stream.Length);
    obj_Doc.Image_Data = bytes;
}
else
{
    obj_Doc.Image_Data = null;
}

  HTML Code

<div class="col-sm-6">
    <div class="form-group">
        <div class="profile-upload">
            <div class="upload-img"> 
                <asp:Image ID="imgDoctor" runat="server" Height="40px" Width="40px" class="rounded-circle m-r-5" />
            </div>
            <div class="upload-input">
                <asp:FileUpload ID="fuImage" runat="server" class="form-control" />
            </div>
        </div>
    </div>
</div>
Posted 7 months ago

Hi pratikshir,

Refer below sample code.

HTML

<div class="col-sm-6">
    <div class="form-group">
        <div class="profile-upload">
            <div class="upload-img">
                <asp:Image ID="imgDoctor" runat="server" Height="40px" Width="40px" class="rounded-circle m-r-5" />
            </div>
            <div class="upload-input">
                <asp:FileUpload ID="fuImage" runat="server" class="form-control" />
            </div>
        </div>
        <asp:Button Text="Update" runat="server" OnClick="Update" />
    </div>
</div>

Namespaces

C#

using System.Data;
using System.Data.SqlClient;
using System.Configuration;

VB.Net

Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        SqlConnection con = new SqlConnection(constr);
        SqlCommand cmd = new SqlCommand("SELECT Image_Data FROM tblFiles", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        if (ds.Tables[0].Rows[0]["Image_Data"] != DBNull.Value)
        {
            string imageUrl = "data:image/jpg;base64," + Convert.ToBase64String((byte[])ds.Tables[0].Rows[0]["Image_Data"]);
            imgDoctor.ImageUrl = imageUrl;
        }
    }
}

protected void Update(object sender, EventArgs e)
{
    string url = imgDoctor.ImageUrl;
    byte[] bytes = Convert.FromBase64String(imgDoctor.ImageUrl.Split(',')[1]);
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection conn = new SqlConnection(constr))
    {
        string sql = "UPDATE tblFiles SET Data=@Data WHERE Id= @Id";
        using (SqlCommand cmd = new SqlCommand(sql, conn))
        {
            cmd.Parameters.AddWithValue("@Id", 1);
            cmd.Parameters.AddWithValue("@Data", bytes);
            conn.Open();
            cmd.ExecuteNonQuery();
            conn.Close();
        }
    }
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Dim con As SqlConnection = New SqlConnection(constr)
        Dim cmd As SqlCommand = New SqlCommand("SELECT Image_Data FROM tblFiles", con)
        Dim da As SqlDataAdapter = New SqlDataAdapter(cmd)
        Dim ds As DataSet = New DataSet()
        da.Fill(ds)

        If ds.Tables(0).Rows(0)("Image_Data") <> Nothing Then
            Dim imageUrl As String = "data:image/jpg;base64," & Convert.ToBase64String(CType(ds.Tables(0).Rows(0)("Image_Data"), Byte()))
            imgDoctor.ImageUrl = imageUrl
        End If
    End If
End Sub

Protected Sub Update(ByVal sender As Object, ByVal e As EventArgs)
    Dim url As String = imgDoctor.ImageUrl
    Dim bytes As Byte() = Convert.FromBase64String(imgDoctor.ImageUrl.Split(","c)(1))
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using conn As SqlConnection = New SqlConnection(constr)
        Dim sql As String = "UPDATE tblFiles SET Data=@Data WHERE Id= @Id"
        Using cmd As SqlCommand = New SqlCommand(sql, conn)
            cmd.Parameters.AddWithValue("@Id", 1)
            cmd.Parameters.AddWithValue("@Data", bytes)
            conn.Open()
            cmd.ExecuteNonQuery()
            conn.Close()
        End Using
    End Using
End Sub