当我将 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/