转换为字节数组时图像数据丢失

Image data loss when converting to byte array

我正在尝试使用 MemoryStream 将图像转换为字节数组,但是,当我恢复图像时,图像看起来不一样了。

我制作了一个简单的 Form 应用来展示这个问题。我在这个例子中使用 google chrome 图标:

var process = Process.GetProcessById(3876); // found pid manually
var image = Icon.ExtractAssociatedIcon(process.MainModule.FileName).ToBitmap();
pictureBox1.Image = image;

byte[] imageBytes;
using (var ms = new MemoryStream())
{
    image.Save(ms, ImageFormat.Bmp);
    imageBytes = ms.ToArray();
}

using (var ms = new MemoryStream(imageBytes))
{
    pictureBox2.Image = (Bitmap) Image.FromStream(ms);
}

结果:

知道我在这里遗漏了什么吗?


更新 我能够使用以下代码获得正确的字节:

var converter = new ImageConverter();
var imageBytes = (byte[]) converter.ConvertTo(image, typeof(byte[]));

不过还是想知道内存流是怎么回事..

Icons are complicated. When they contain transparent parts, converting to BMP or JPG 。您也不需要 ImageConverter 它几乎可以完成您的代码在没有 BMP 转换的情况下所做的事情:

var process = Process.GetProcessById(844); // found pid manually
var image = Icon.ExtractAssociatedIcon(process.MainModule.FileName).ToBitmap();
pb1.Image = image;

byte[] imageBytes; 

using (var ms = new MemoryStream())
{ 
    image.Save(ms, ImageFormat.Png);        // PNG for transparency
    ms.Position = 0;
    pb2.Image = (Bitmap)Image.FromStream(ms);                
}

ImageConverter Reference Source