0

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:

image before and image after

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..

1
  • Try to use the 32bit format like PNG. The circle needs probably transparency. Commented Jul 6, 2016 at 0:01

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.