从位图流 C# 计算 MD5 的问题

Ysz*_*zty 7 c# md5 memorystream image

当我将 Bmp 作为流传递时,函数总是返回,

D4-1D-8C-D9-8F-00-B2-04-E9-80-09-98-EC-F8-42-7E
Run Code Online (Sandbox Code Playgroud)

但文件正确保存在磁盘上。当我从磁盘加载 bpm 时,函数返回正确的 MD5。同时传递“new Bitmap(int x, int y);” 不同的值返回相同的 MD5。

为什么会发生?

    public static string GetMD5Hash()
    {

        Bitmap Bmp = new Bitmap(23, 46); // 
        using (Graphics gfx = Graphics.FromImage(Bmp))
        using (SolidBrush brush = new SolidBrush(Color.FromArgb(32, 44, 2)))
        {
            gfx.FillRectangle(brush, 0, 0, 23, 46);
        }



        using (var md5 = MD5.Create())
        {
            using (MemoryStream memoryStream = new MemoryStream())
            {
                Bmp.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Bmp);
 \//EDITED:     Bmp.Save(@"C:\Test\pizdanadysku.bmp"); // Here saving file on disk, im getting diffrent solid color

                return BitConverter.ToString(md5.ComputeHash(memoryStream)); //Always return D4-1D-8C-D9-8F-00-B2-04-E9-80-09-98-EC-F8-42-7E - I noticed that is MD5 of empty 1x1px Bmp file
            } 
        }
    }
Run Code Online (Sandbox Code Playgroud)

有人可以解释这种奇怪的行为吗?

AAA*_*ddd 9

由于各种原因(包括某些流只能被读取,例如NetworkStream),流操作往往只会向前推进,因此保存图像可能只是将流推进到最后。

此外,并由各种有用的编辑(@jpa)指出。

D4-1D-8C-D9-8F-00-B2-04-E9-80-09-98-EC-F8-42-7E
Run Code Online (Sandbox Code Playgroud)

是空字符串的经典 MD5 和。

我的直觉是您只需要重置流的位置即可获得所需的结果

memoryStream.Seek(0, SeekOrigin.Begin)
// or 
memoryStream.Position = 0;
Run Code Online (Sandbox Code Playgroud)