2014-11-22 121 views
0

我遇到了一個困境,我需要將一個位圖轉換爲一個字節數組,但我需要某種方式,我需要做到這一點,爲了演示這些位圖是單色的,這就是我需要做的:如何將3x3像素.bmp轉換爲3x3字節數組?

讓說,#是255的RGB值,255,255的密鑰,並且@爲0,0的RGB值,0.1

@@@

@ ##

@#@

我需要那個轉換erted到這樣的事情:

0,0,0

0,255,255

0,255,0

難道這可能做到嗎?

+2

是的,我認爲這可以做到。你有什麼嘗試? – 2014-11-22 14:25:42

+0

在使用另一個stackoverflow答案之前,我試過了這個,但問題在於它將整個文件輸出爲字節答案,我只想要可見信息,如顏色。 – Mavain 2014-11-22 14:30:12

+0

在位圖中有所有的像素。會有什麼問題?你有文件中的數據嗎?哪種格式?你有嘗試過什麼嗎?以'位圖bmp =新位圖(「yourImageFile」)開始; for(int y .. for(int x .. Color c = bmp.GetPixel(x,y); if(c == Color.White)..' – TaW 2014-11-22 14:49:37

回答

1

首先得到字節:

ImageConverter

public static byte[] ImageToByte(Image img) 
{ 
    ImageConverter converter = new ImageConverter(); 
    return (byte[])converter.ConvertTo(img, typeof(byte[])); 
} 

或內存流

public static byte[] ImageToByte2(Image img) 
{ 
    byte[] byteArray = new byte[0]; 
    using (MemoryStream stream = new MemoryStream()) 
    { 
     img.Save(stream, System.Drawing.Imaging.ImageFormat.Png); 
     stream.Close(); 

     byteArray = stream.ToArray(); 
    } 
    return byteArray; 
} 

然後把它變成你想要的多維數組。

byte[][] multi = new byte[height][]; 
for (int y = 0; y < height; ++y) 
{ 
    multi[y] = new byte[width]; 
    // Do optional translation of the byte into your own format here 
    // For purpose of illustration, here is a straight copy 
    Array.Copy(bitmapBytes, width * y, multi[y], 0, width); 
} 
+0

我需要獲取可見信息的字節,比如每個像素的顏色,而不是整個位圖 – Mavain 2014-11-22 14:41:41

+0

然後你需要閱讀:http: //en.wikipedia.org/wiki/BMP_file_format,跳過組成文件頭的前X個字節,即在我的例子中不是(width * y),它將是(headerSize +(width * y))。你也許還會發現Image已經刪除了文件的某些部分,所以你需要對此進行解釋 – 2014-11-22 14:46:46

+0

原來,位圖有一個.GetPixel函數,仍然,感謝你的建議!:) – Mavain 2014-11-22 15:04:02