简体   繁体   中英

Image data loss when converting to byte array

I'm trying to use a MemoryStream to turn an image into a byte array, however, the image looks different when I recover it.

I made a simple Form app to show the issue. I'm using the google chrome Icon for this example:

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);
}

Result:

之前的图像和之后的图像

Any idea what I'm missing here?


Update I was able to get the proper bytes using the following code:

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

Would still like to know whats up with the Memory stream though..

Icons are complicated . When they contain transparent parts, converting to BMP or JPG almost always seems to end badly . You also dont need ImageConverter it is doing almost what your code does without the BMP conversion:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM