C# Programming > Data


Bitmap Hash C# Example

First we are going to create a simple image:

using System.Drawing;

Bitmap simpleImage = new Bitmap(30, 30);
using (Graphics g = Graphics.FromImage(simpleImage))

The result is a simple 30 pixel by 30 pixel red square. Not the most inspired of pictures, but remember that the hashing will work with any image.

Now that we have the bitmap, we need the raw byte data. We will use a simple method from the image to byte article.

ImageConverter converter = new ImageConverter();
byte[] rawImageData = converter.ConvertTo(simpleImage, typeof(byte[])) as byte[];

This method is nice because it blissfully let's us ignore image formats and such. Remember that it is up to you to select the best method for your .NET application. For example, here is a much faster way to do it (I adapted the C# code from a comment in this article):

using System.Drawing.Imaging;
System.Runtime.InteropServices; byte[] rawImageData = new byte[30 * 30]; BitmapData bmpd = simpleImage.LockBits(new Rectangle(0, 0, 30, 30), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); Marshal.Copy(bmpd.Scan0, rawImageData, 0, 30 * 30); simpleImage.UnlockBits(bmpd);

This method requires the application and class/function to allow unsafe code. If you do not know what that is, don't worry about it. The point here is, there are a lot of ways to get byte data from an image.

Given that we have the byte data (somehow), we can now calculate the hash value:

MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] hash = md5.ComputeHash(rawImageData);

In this case we used the MD5 algorithm. You can of course use countless other algorithms. As long as you keep these two things consistent: a) the image to byte function and b) the hashing algorithm, the hash value for a given image will always be the same.

One last note is that the hash value is in an array of bytes. This can be converted to pretty much any other format. It is up to you and your .NET application.

Page 1
<< Image Hashing Explanation

Back to C# Article List