[英]Convert byte to BitmapImage uwp c#
I try to convert a white bitmapImage to black. 我尝试将白色的bitmapImage转换为黑色。 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.
所以我有一个byte [] PixelArray,这很好,但是当我尝试使用此数组创建我的黑色图像时,它不起作用。 Here is my code :
这是我的代码:
var stream = new InMemoryRandomAccessStream();
await stream.WriteAsync(byteArray.AsBuffer());
stream.Seek(0);
await image.SetSourceAsync(stream);
Thanks guys 多谢你们
As @Clemens said, we should be able to use WriteableBitmap
. 正如@Clemens所说,我们应该能够使用
WriteableBitmap
。 We can get the Width and the Height by BitmapDecoder.PixelWidth
and BitmapDecoder.PixelHeight
property. 我们可以通过
BitmapDecoder.PixelWidth
和BitmapDecoder.PixelHeight
属性获得Width和Height。 Then we can use WriteableBitmap.PixelBuffer
to set the bytes Array to the WriteableBitmap
. 然后,我们可以使用
WriteableBitmap.PixelBuffer
将字节数组设置为WriteableBitmap
。
PixelBuffer cannot be written to directly, however, you can use language-specific techniques to access the buffer and change its contents.
无法直接写入PixelBuffer,但是,可以使用特定于语言的技术来访问缓冲区并更改其内容。 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.
若要从C#或Microsoft Visual Basic访问像素内容,可以使用AsStream扩展方法以流的形式访问基础缓冲区。
For more info, see Remarks of the WriteableBitmap.PixelBuffer
. 有关更多信息,请参见
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
. 要将
WriteableBitmap
转换为BitmapImage
,我们应该能够对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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.