2016-12-15 86 views
0

我尝试将白色bitmapImage转换为黑色。所以我有一个字节[] PixelArray,这是很好的,但是当我尝试使用这个数组来创建我的黑色图像它不起作用。这里是我的代码:将字节转换为BitmapImage uwp c#

var stream = new InMemoryRandomAccessStream(); 
await stream.WriteAsync(byteArray.AsBuffer()); 
stream.Seek(0); 
await image.SetSourceAsync(stream); 

谢谢你们

+1

'BitmapImage.SetSourceAsync'不接受原始像素缓冲器,但只有一个编码的位图的帧,例如一个PNG或JPEG。您可以改用WriteableBitmap。 – Clemens

+0

如何获取字节数组?如果你从中得到它,我们应该能够通过你的方法得到它。 –

+0

嗨Jayden顾,感谢您的评论。这是我如何得到我的数组: – moh67

回答

1

正如@Clemens说,我们应该能够使用WriteableBitmap。我们可以通过BitmapDecoder.PixelWidthBitmapDecoder.PixelHeight属性获得宽度和高度。然后我们可以使用WriteableBitmap.PixelBuffer将字节数组设置为WriteableBitmap

PixelBuffer不能直接写入,但是,您可以使用语言特定的技术访问缓冲区并更改其内容。 要从C#或Microsoft Visual Basic中访问像素内容,可以使用AsStream扩展方法以流的形式访问基础缓冲区。

欲了解更多信息,请参阅WriteableBitmap.PixelBuffer的备注。

例如:

IRandomAccessStream random = await RandomAccessStreamReference.CreateFromUri(ImageWhite.UriSour‌​ce).OpenReadAsync(); 
BitmapDecoder decoder = await BitmapDecoder.CreateAsync(random); 
PixelDataProvider pixelData = await decoder.GetPixelDataAsync(); 
var PixelArray = pixelData.DetachPixelData(); 
WriteableBitmap bitmap = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight); 
await bitmap.PixelBuffer.AsStream().WriteAsync(PixelArray, 0, PixelArray.Length); 
MyImage.Source = bitmap; 

更新:

转换的WriteableBitmapBitmapImage,我们应该能够到流从WriteableBitmap编码。

例如:

InMemoryRandomAccessStream inMemoryRandomAccessStream = new InMemoryRandomAccessStream(); 
BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, inMemoryRandomAccessStream); 
Stream pixelStream = bitmap.PixelBuffer.AsStream(); 
byte[] pixels = new byte[pixelStream.Length]; 
await pixelStream.ReadAsync(pixels, 0, pixels.Length); 
encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore, (uint)bitmap.PixelWidth, (uint)bitmap.PixelHeight, 96.0, 96.0, pixels); 
await encoder.FlushAsync(); 
BitmapImage bitmapImage = new BitmapImage(); 
bitmapImage.SetSource(inMemoryRandomAccessStream); 
MyImage.Source = bitmapImage; 
+0

感谢您的评论。但MyImage是一个bitmapImage,我不知道如何将writeableBitmap转换为bitmapimage。你知不知道怎么 ? – moh67

+0

正如@Clemens所说,BitmapImage.SetSourceAsync不接受原始像素缓冲区,而只接受编码位图帧,例如一个PNG或JPEG。另外你为什么要获得'BitmapImage'?看来我们可以直接将WriteableBitmap设置为Image.Source。 –

+0

感谢您的回答。我的imageSource是一个btimapImage,我的应用程序做了一些其他的东西,我需要将我的位图转换为bitmapImage – moh67