Search - Articles
DevASP.NET for ASP.NET, VB.NET, XML and C# (C-Sharp) Developers Tuesday, March 03, 2009
Dev Articles
Search Directory
ASP.NET
VB.Net
C-Sharp
SQL Server
 

How to compare two images in ASP.NET

Author: Richard Wand
Download Source Code : 1363_CompareTwoImages.zip

This article will explain how we can compare two images in ASP.NET.

 

You can compare images using code snippet provided in this article whether you are uploading your images or you are getting images from database stored in binary format.

  1. Create new website in Visual Studio 2010
  2. Add two FileUpload controls, a Button and a Label in aspx page of a web form

    <asp:FileUpload ID="FileUpload1" runat="server" />
    <br />
    <asp:FileUpload ID="FileUpload2" runat="server" />
    <br />
    <asp:Button ID="btnUpload" runat="server" Text="Upload"
        onclick="btnUpload_Click" />
    <br />
    <asp:Label ID="lblMessage" runat="server" ></asp:Label>
     
  3. Add a folder in your website with the name of Images
     
  4. We have to use following namespaces in our code

    C#
     
    using System.IO;
    using System.Drawing;
    using System.Security.Cryptography;
     
    VB.NET

    Imports System.IO
    Imports System.Drawing
    Imports System.Security.Cryptography
     
  5. Write below function in your code file for image comparison

    C#
     
    public bool CompareTwoImages(Bitmap img1Bitmap, Bitmap img2Bitmap)
    {
        ImageConverter imgConverter = new ImageConverter();
     
        byte[] img1Bytes = new byte[1];
        byte[] img2Bytes = new byte[1];
     
        img1Bytes = (byte[])imgConverter.ConvertTo(img1Bitmap, img1Bytes.GetType());
        img2Bytes = (byte[])imgConverter.ConvertTo(img2Bitmap, img2Bytes.GetType());
     
        SHA256Managed sha256Managed = new SHA256Managed();
     
        byte[] hash1 = sha256Managed.ComputeHash(img1Bytes);
        byte[] hash2 = sha256Managed.ComputeHash(img2Bytes);
     
        int i = 0;
        while (i < hash1.Length && i < hash2.Length)
        {
            if (hash1[i] == hash2[i])
            {
                return true;
            }
            else
            {
                return false;
            }
            i++;
        }
        return false;
    }
     
    VB.NET
     
    Public Function CompareTwoImages(ByVal img1Bitmap As Bitmap, ByVal img2Bitmap As Bitmap) As Boolean
        Dim imgConverter As New ImageConverter()
     
        Dim img1Bytes As Byte() = New Byte(0) {}
        Dim img2Bytes As Byte() = New Byte(0) {}
     
        img1Bytes = DirectCast(imgConverter.ConvertTo(img1Bitmap, img1Bytes.[GetType]()), Byte())
        img2Bytes = DirectCast(imgConverter.ConvertTo(img2Bitmap, img2Bytes.[GetType]()), Byte())
     
        Dim sha256Managed As New SHA256Managed()
     
        Dim hash1 As Byte() = sha256Managed.ComputeHash(img1Bytes)
        Dim hash2 As Byte() = sha256Managed.ComputeHash(img2Bytes)
     
        Dim i As Integer = 0
        While i < hash1.Length AndAlso i < hash2.Length
            If hash1(i) = hash2(i) Then
                Return True
            Else
                Return False
            End If
            i += 1
        End While
        Return False
    End Function
     
    This function takes two arguments of type Bitmap class for both images returns Boolean value. Create instance of ImageConverter class and also create two byte arrays. Convert Bitmap objects to byte arrays for both images. Create an instance of SHA256Managed class. This class is used to compute hash for data. Now compute hash for both images. Here I have used While loop to loop through both arrays and to compare each byte. This function returns false if both images are nor equal and returns true if images are equal.
     
  6. Now Add a Button click event and write code below in it

    C#
     
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile && FileUpload2.HasFile)
        {
            string fileName1 = FileUpload1.PostedFile.FileName;
            string fileName2 = FileUpload2.PostedFile.FileName;
            int img1Length = FileUpload1.PostedFile.ContentLength;
            int img2Length = FileUpload2.PostedFile.ContentLength;
     
            if (fileName1 == fileName2)
            {
                lblMessage.Text = "Images are same";
            }
            else
            {
                BinaryReader img1Reader = new BinaryReader(FileUpload1.PostedFile.InputStream);
                BinaryReader img2Reader = new BinaryReader(FileUpload2.PostedFile.InputStream);
     
                byte[] img1Bytes = img1Reader.ReadBytes(img1Length);
                byte[] img2Bytes = img2Reader.ReadBytes(img2Length);
     
                ImageConverter imgConverter = new ImageConverter();
     
                Image img1 = (Image)imgConverter.ConvertFrom(img1Bytes);
                Image img2 = (Image)imgConverter.ConvertFrom(img2Bytes);
     
                Bitmap img1Bitmap = new Bitmap(img1);
                Bitmap img2Bitmap = new Bitmap(img2);
     
                bool result = CompareTwoImages(img1Bitmap, img2Bitmap);
     
                if (result == true)
                {
                    lblMessage.Text = "Images are same";
                }
                else
                {
                    string path = Server.MapPath("~/Images/");
     
                    FileUpload1.PostedFile.SaveAs(path + fileName1);
                    FileUpload2.PostedFile.SaveAs(path + fileName2);
                    lblMessage.Text = "Images uploaded";
                } 
            }
        }
    }
     
    VB.NET

    Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnUpload.Click
        If FileUpload1.HasFile AndAlso FileUpload2.HasFile Then
            Dim fileName1 As String = FileUpload1.PostedFile.FileName
            Dim fileName2 As String = FileUpload2.PostedFile.FileName
            Dim img1Length As Integer = FileUpload1.PostedFile.ContentLength
            Dim img2Length As Integer = FileUpload2.PostedFile.ContentLength
     
            If fileName1 = fileName2 Then
                lblMessage.Text = "Images are same"
            Else
                Dim img1Reader As New BinaryReader(FileUpload1.PostedFile.InputStream)
                Dim img2Reader As New BinaryReader(FileUpload2.PostedFile.InputStream)
     
                Dim img1Bytes As Byte() = img1Reader.ReadBytes(img1Length)
                Dim img2Bytes As Byte() = img2Reader.ReadBytes(img2Length)
     
                Dim imgConverter As New ImageConverter()
     
                Dim img1 As Image = DirectCast(imgConverter.ConvertFrom(img1Bytes), Image)
                Dim img2 As Image = DirectCast(imgConverter.ConvertFrom(img2Bytes), Image)
     
                Dim img1Bitmap As New Bitmap(img1)
                Dim img2Bitmap As New Bitmap(img2)
     
                Dim result As Boolean = CompareTwoImages(img1Bitmap, img2Bitmap)
     
                If result = True Then
                    lblMessage.Text = "Images are same"
                Else
                    Dim path As String = Server.MapPath("~/Images/")
     
                    FileUpload1.PostedFile.SaveAs(path + fileName1)
                    FileUpload2.PostedFile.SaveAs(path + fileName2)
                    lblMessage.Text = "Images uploaded"
                End If
            End If
        End If
    End Sub
     
    Check if both FileUpload controls have file and then get file names and length of the both files. You can also check file extension for images. If both files have same name then no need to compare images further. Create BinaryReader instances for both files. Here you can get binary data from database or from posted file. We need to convert binary data to Bitmap instances to pass these images to our function. First convert these to images and then pixel data. Call our function by passing these Bitmap instances and get the Boolean values. If result is true then our images are same and if result is false then you can save files to your server.
     
  7. Start debugging and upload same and different files to see result. 
   
Add Article Comment:
Name :
Email Address :
   
Comments :
 
   
<< How to create DropDownList and populate items using JQuery in ASP.NET

Disclaimer - Privacy
© 2002-2017 DevASP.net