2016-12-15 87 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