本文介绍了将字节转换为 BitmapImage uwp c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我尝试将白色位图图像转换为黑色.所以我有一个 byte[] PixelArray,这很好,但是当我尝试使用这个数组来创建我的黑色图像时,它不起作用.这是我的代码:

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);

谢谢各位

推荐答案

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

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 不能直接写入,但是,您可以使用特定于语言的技术来访问缓冲区并更改其内容.要从 C# 或 Microsoft Visual Basic 访问像素内容,您可以使用 AsStream 扩展方法以流的形式访问底层缓冲区.

有关详细信息,请参阅 WriteableBitmap.PixelBuffer.

For more info, see Remarks of the 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;

更新:

要将WriteableBitmap 转换为BitmapImage,我们应该能够对来自WriteableBitmap 的流进行编码.

To Convert the WriteableBitmap to BitmapImage, we should be able to encode the stream from 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;

这篇关于将字节转换为 BitmapImage uwp c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 01:27