2010-07-28 154 views
2

我以128 x 128的雙精度數組開始,並將它轉換爲每個double的比例值的1D字節數組。byte []轉換爲灰度BitmapImage

我然後藉此陣列的字節並把它變成一個內存流(下面dataStream),並嘗試並將它放入一個BitmapImage像這樣:

imgScan.Width = 128; 
imgScan.Height = 128; 
BitmapImage bi = new BitmapImage(); 
bi.SourceRect = new Int32Rect(0, 0, width, height); 
bi.StreamSource = dataStream; 
imgScan.Source = bi; 

這裏imgScanSystem.Windows.Controls.Image

這不會產生預期的圖像(我只是得到一個白色方塊)。

我應該怎麼做?

回答

1

我想你會發現在你的代碼中,流應該包含一個完整的圖像文件,而不是原始的數據塊。下面是從數據塊進行位圖(它不是灰度圖,但你可能會得到的想法):

const int bytesPerPixel = 4; 
int stride = bytesPerPixel * pixelsPerLine; 
UInt32[] pixelBytes = new uint[lineCount * pixelsPerLine]; 

for (int y = 0; y < lineCount; y++) 
{ 
    int destinationLineStart = y * pixelsPerLine; 
    int sourceLineStart = y * pixelsPerLine; 
    for (int x = 0; x < pixelsPerLine; x++) 
    { 
     pixelBytes[x] = _rgbPixels[x].Pbgr32; 
    } 
} 
var bmp = BitmapSource.Create(pixelsPerLine, lineCount, 96, 96, PixelFormats.Pbgra32, null, pixelBytes, stride); 
bmp.Freeze(); 
return bmp; 

你已經做了位在嵌套循環(使字節數組),但我離開它在所以你可以看到什麼來創建之前

+0

謝謝,威爾。還有一個問題:步幅是什麼意思?我可以看到你已經將它設置爲'bytesPerPixel * pixelsPerLine',但我對這個術語不熟悉。 – 2010-07-28 15:17:48

+0

步幅是從一行的開始到數據塊中下一行的開始所需的字節數。在你的情況下,它將是你的字節塊的寬度,但是在例如你有三個字節像素(RGB888也許)的情況下,那麼步幅通常將是四個字節的倍數,即使(3x數字的像素)不是四的倍數本身。這就是說,線條總是從一個很好對齊的內存地址開始的,而且從人們關注像這樣的詳細信息的時代開始,這真的是一個宿醉。 – 2010-07-28 16:14:25

+0

輝煌。謝謝,威爾。 – 2010-07-29 07:06:44