2016-07-05 87 views
0

我想使用MemoryStream將圖像轉換爲字節數組,但是,恢復它時圖像看起來不同。轉換爲字節數組時圖像數據丟失

我做了一個簡單的Form應用程序來顯示該問題。我使用谷歌的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); 
} 

結果:

image before and image after

任何想法,我在這裏失蹤?


更新我能得到使用下面的代碼正確的字節:

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

還是想知道怎麼了,雖然內存流..

+0

嘗試使用像PNG的32位格式。該圈子可能需要透明度。 – 2016-07-06 00:01:18

回答

3

Icons are complicated。當它們包含透明部分時,轉換爲BMP或JPG almost always seems to end badly。您也不需要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