2010-07-28 86 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