Need MD5 hash for an in memory System.Drawing.Image

前端 未结 3 1730
难免孤独
难免孤独 2020-12-18 01:42

Need MD5 hash for an in memory System.Drawing.Image

3条回答
  •  隐瞒了意图╮
    2020-12-18 02:09

    A simple sample, based on the sample in MSDN; note that this hash is dependent on the internal representation of the image and will not correspond to the hash created from a 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 are going to use the hash for you should consider the fact that MD5 is no longer state of the art and that there are better hash functions available if you need a strong hash.

提交回复
热议问题