繁体   English   中英

Windows通用应用程序中位图(System.Drawing)的替代

[英]Alternative of Bitmap (System.Drawing) in Windows Universal Application

我正在开发一个Windows通用应用程序,它将在ARM体系结构( RaspberryPi 3,操作系统:Windows IoT )上运行。

我面临的问题是UWP不允许使用很多标准的.Net库,例如“ System.Drawing”

我目前有一个IntPtr ,其中包含图像的原始数据,我需要将其用作位图 ,这在这种情况下当然是不可能的。 有没有其他可能的选择。

我一直在寻找BitmapImage,但没有找到任何解决方案。

我也尝试过将IntPtr转换为Byte [],但是在UWP中无法将数组转换为ImageBitmapImage

因为我是C#编程的新手,所以请放心。

我想要的只是来自IntPtr的任何类型的位图或图像

提前致谢!

我想追加更多内容,但是我还不能编辑评论,因此SO自动将原始回复设为评论。 基本上看来,您的困境很常​​见,但是您必须考虑第三方解决方案。

要将IntPtrByte[] ,我们可以使用Marshal.Copy方法。 它将数据从一维,托管的8位无符号整数数组复制到非托管的内存指针。

然后,我们可以使用WriteableBitmap类将Byte []设置为WriteableBitmap

WriteableBitmap的图像源数据是基础像素缓冲区。 无法直接写入PixelBuffer,但是,可以使用特定于语言的技术来访问缓冲区并更改其内容。

若要从C#或Microsoft Visual Basic访问像素内容,可以使用AsStream扩展方法以流的形式访问基础缓冲区。

有关更多信息,请参见WriteableBitmap的备注

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

例如:

private byte[] managedArray;

private async void Button_Click(object sender, RoutedEventArgs e)
{
    Windows.Storage.Streams.IRandomAccessStream random = await Windows.Storage.Streams.RandomAccessStreamReference.CreateFromUri(new Uri("ms-appx:///Assets/sunset.jpg")).OpenReadAsync();
    Windows.Graphics.Imaging.BitmapDecoder decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(random);
    Windows.Graphics.Imaging.PixelDataProvider pixelData = await decoder.GetPixelDataAsync();
    byte[] buffer = pixelData.DetachPixelData();
    unsafe
    {
        fixed (byte* p = buffer)
        {
            IntPtr ptr = (IntPtr)p;
            managedArray = new byte[buffer.Length];
            Marshal.Copy(ptr, managedArray, 0, buffer.Length);
        }
    }
    WriteableBitmap bitmap = new WriteableBitmap((int)decoder.PixelWidth, (int)decoder.PixelHeight);
    await bitmap.PixelBuffer.AsStream().WriteAsync(managedArray, 0, managedArray.Length);
    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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM