开发者

byte[] to gray scale BitmapImage

开发者 https://www.devze.com 2023-01-09 10:18 出处:网络
I start out with a 128 x 128 array of doubles and turn that into a 1D array of bytes with proportional values for each double.

I start out with a 128 x 128 array of doubles and turn that into a 1D array of bytes with proportional values for each double.

I then take this array of bytes and turn it into a memory stream (dataStream below) and try and put that into a BitmapImage like so:

imgScan.Width = 128;
imgScan.Height = 128;
BitmapImage bi = new BitmapImage();
bi.SourceRect = new In开发者_StackOverflowt32Rect(0, 0, width, height);
bi.StreamSource = dataStream;
imgScan.Source = bi;

Here imgScan is a System.Windows.Controls.Image

This doesn't produce the expected image (I just get a white square).

How should I be going about this?


I think you'll find that in your code, the stream should contain a complete image file, not a raw block of data. Here's making a Bitmap from a block of data (it's not greyscale, but you might get the idea):

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;

You've already done the bit in the nested loops (making the byte array), but I left it in so you can see what comes before the Create

0

精彩评论

暂无评论...
验证码 换一张
取 消