Need MD5 hash for System.Drawing.Image memory

Requires MD5 hash for System.Drawing.Image memory

+6
c # image hash md5
source share
3 answers

Here is the basic snippet. See also @JaredReisinger comment for some questions.

using System.Security.Cryptography; using System.Text; using System.Drawing.Imaging; // ... // get the bytes from the image byte[] bytes = null; using( MemoryStream ms = new MemoryStream() ) { image.Save(ms,ImageFormat.Gif); // gif for example bytes = ms.ToArray(); } // hash the bytes MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); byte[] hash = md5.ComputeHash(bytes); // make a hex string of the hash for display or whatever StringBuilder sb = new StringBuilder(); foreach (byte b in hash) { sb.Append(b.ToString("x2").ToLower()); } 
+5
source share

A simple example based on a sample on MSDN ; note that this hash is dependent on the internal representation of the image and will not match the hash created from the file.

 using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Security.Cryptography; using System.Text; class Program { static string getMd5Hash(byte[] buffer) { MD5 md5Hasher = MD5.Create(); byte[] data = md5Hasher.ComputeHash(buffer); StringBuilder sBuilder = new StringBuilder(); for (int i = 0; i < data.Length; i++) { sBuilder.Append(data[i].ToString("x2")); } return sBuilder.ToString(); } static byte[] imageToByteArray(Image image) { MemoryStream ms = new MemoryStream(); image.Save(ms, ImageFormat.Bmp); return ms.ToArray(); } static void Main(string[] args) { Image image = Image.FromFile(@"C:\tmp\Jellyfish.jpg"); byte[] buffer = imageToByteArray(image); string md5 = getMd5Hash(buffer); } } 

To be able to use the MD5 class, you need to add a reference to System.Security .

Depending on what you intend to use for the hash, you should consider the fact that MD5 is no longer up to date and that there are better hash functions if you need a strong hash.

+2
source share

Thanks to the other guys who answered. Here is what I did:

 MemoryStream ms = new MemoryStream() image.Save(ms, ImageFormat.Png); byte[] imgBytes = ms.ToArray(); MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); byte[] hash = md5.ComputeHash(imgBytes); string imageMD5 = BitConverter.ToString(hash).Replace("-", "").ToLower(); ms.Dispose(); 
+1
source share

All Articles