Reputation: 43
I try to convert a white bitmapImage to black. So i have a byte[] PixelArray, which is good but when i try to use this array to create my black image it doesn't work. Here is my code :
var stream = new InMemoryRandomAccessStream();
await stream.WriteAsync(byteArray.AsBuffer());
stream.Seek(0);
await image.SetSourceAsync(stream);
Thanks guys
Upvotes: 1
Views: 3282
Reputation: 3286
As @Clemens said, we should be able to use WriteableBitmap
. We can get the Width and the Height by BitmapDecoder.PixelWidth
and BitmapDecoder.PixelHeight
property. Then we can use WriteableBitmap.PixelBuffer
to set the bytes Array to the WriteableBitmap
.
PixelBuffer cannot be written to directly, however, you can use language-specific techniques to access the buffer and change its contents. To access the pixel content from C# or Microsoft Visual Basic, you can use the AsStream extension method to access the underlying buffer as a stream.
For more info, see Remarks of the WriteableBitmap.PixelBuffer
.
For example:
IRandomAccessStream random = await RandomAccessStreamReference.CreateFromUri(ImageWhite.UriSource).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;
Update:
To Convert the WriteableBitmap
to BitmapImage
, we should be able to encode the stream from WriteableBitmap
.
For example:
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;
Upvotes: 2