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

标签 c# image md5 memorystream

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

D4-1D-8C-D9-8F-00-B2-04-E9-80-09-98-EC-F8-42-7E
但文件正确保存在磁盘上。
当我从磁盘加载 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
            } 
        }
    }
有人可以解释这种奇怪的行为吗?

最佳答案

由于各种原因(包括某些流只能被读取,例如 NetworkStream ),流操作往往只会向前移动,因此保存图像可能只是将流推进到最后。
此外,并由各种有帮助的编辑指出 (@jpa)。

D4-1D-8C-D9-8F-00-B2-04-E9-80-09-98-EC-F8-42-7E
是空字符串的经典 MD5 和。
我的直觉是您只需要重置流的位置即可获得所需的结果
memoryStream.Seek(0, SeekOrigin.Begin)
// or 
memoryStream.Position = 0;

关于c# - 从位图流 C# 计算 MD5 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63665162/

相关文章:

encryption - MD5 生成如何取决于文件大小?

c# - 如何从 SourceForge 获取 MD5 码

c# - 处理 API 的并行 POST

c# - 数据库第一个EF和ASP.NET Core 3 Web API在Azure上发布,连接字符串错误

javascript - jQuery 数组中的下一个和上一个

JavaFX HTMLEditor - 使用绝对路径插入本地镜像

javascript - 使用图像映射时鼠标悬停时图像闪烁javascript

c# - 将 List<Guid> 转换为 List<Guid? >

c# - 使用主机作为 IP 地址的 SMTP 发送邮件时无法解析远程名称

windows - 如何在 Windows 上获取 RSA 公钥的 MD5 指纹?