Compare Binary image in database with another image in ASP.Net using C# .Net

Last Reply on Oct 29, 2014 04:53 AM By Azim

Posted on Oct 28, 2014 04:21 AM

Sir,

    i want to compare two images.One of the image is the fileuploded image and another one is database stored image.The image is stored inside database by using the handler.

please help me to solve this problem...

You are viewing reply posted by: Azim on Oct 29, 2014 04:53 AM.
Posted on Oct 29, 2014 04:53 AM Modified on on Oct 29, 2014 05:00 AM

Please refer this code.

For checking this code you need to upload the same image to the table.

HTML

<form id="form1" runat="server">
<div>
    <asp:FileUpload runat="server" ID="FileUpload1" />
    <asp:Button Text="Compare" runat="server" OnClick="CompareImages" />
</div>
</form>

Namespaces

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

C#

protected void CompareImages(object sender, EventArgs e)
{
    if (this.FileUpload1.HasFile)
    {
        Stream fs = FileUpload1.PostedFile.InputStream;
        BinaryReader br = new BinaryReader(fs);
        Byte[] bytes = br.ReadBytes((Int32)fs.Length);
        string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection conn = new SqlConnection(constr))
        {
            string sqlQuery = "SELECT Data from [tblFiles] WHERE Name = @FileName";

            using (SqlCommand cmd = new SqlCommand(sqlQuery, conn))
            {
                cmd.Parameters.AddWithValue("@FileName", Path.GetFileName(this.FileUpload1.PostedFile.FileName));
                conn.Open();
                Byte[] bytes2 = (Byte[])cmd.ExecuteScalar();
                conn.Close();
                if (bytes2 != null)
                {
                    if (bytes.Length == bytes2.Length)
                    {
                        ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Equal Images')", true);
                    }
                    else
                    {
                        ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Images are not equal')", true);
                    }
                }
                else
                {
                    ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('File Not found in the table')", true);
                }
            }
        }
    }
}