如何在Windows Phone 8中将像素字节数组转换为位图图像

时间:2014-04-15 01:13:37

标签: c# windows-phone-8 bitmap bytearray

我想使用像素字节在Windows Phone 8中绘制图像。所以我通过c ++库(c ++ / CLI)得到一些像素字节。但像素数据不包括位图标题。它只是像素字节数组。 这是否可以将像素数据数组转换为位图图像而不使用Windows Phone中的位图标题?

    public void updateImage(byte[] byteArray, UInt32 bufferSize, int cvtWidth, int cvtHeight)
    {
        // I saw this source a lot of search. But It's not work. It makes some exeption.
        BitmapImage bi = new BitmapImage();
        MemoryStream memoryStream = new MemoryStream(byteArray);
        bi.SetSource(memoryStream);

        ImageScreen.Source = bi;
    }

2 个答案:

答案 0 :(得分:1)

您需要使用WriteableBitmap:http://msdn.microsoft.com/en-us/library/windows/apps/windows.ui.xaml.media.imaging.writeablebitmap

然后你可以使用AsStream访问它的PixelBuffer并将该数组保存到流中。

//srcWidth and srcHeight are original image size, needed
//srcData is pixel data array
WriteableBitmap wb = new WriteableBitmap(srcWidth, srcHeight); 

using (Stream stream = wb.PixelBuffer.AsStream()) 
{ 
    await stream.WriteAsync(srcData, 0, srcData.Length); 
} 

修改

正如Proglamour在WIndows Phone中所说,没有PixelBuffer,但是存在一个名为Pixels的属性,它是一个数组。

它无法替换,但它的内容可以这样做:

WriteableBitmap wb = new WriteableBitmap(srcWidth, srcHeight); 
Array.Copy(srcData, wb.Pixels, srcData.Length);

答案 1 :(得分:1)

我解决了这个问题。谢谢你的帮助菲利普。

    public void updateImage(byte[] byteArray, UInt32 bufferSize, int cvtWidth, int cvtHeight)
    {
        Dispatcher.BeginInvoke(() =>
        {
            WriteableBitmap wb = new WriteableBitmap(cvtWidth, cvtHeight);
            System.Buffer.BlockCopy(byteArray, 0, wb.Pixels, 0, byteArray.Length);
            //wb.Invalidate();
            ImageScreen.Source = wb;
        });
    }