[英]Alternative of Bitmap (System.Drawing) in Windows Universal Application
我正在開發一個Windows通用應用程序,它將在ARM體系結構( RaspberryPi 3,操作系統:Windows IoT )上運行。
我面臨的問題是UWP不允許使用很多標准的.Net庫,例如“ System.Drawing”
我目前有一個IntPtr ,其中包含圖像的原始數據,我需要將其用作位圖 ,這在這種情況下當然是不可能的。 有沒有其他可能的選擇。
我一直在尋找BitmapImage,但沒有找到任何解決方案。
我也嘗試過將IntPtr轉換為Byte [],但是在UWP中無法將數組轉換為Image或BitmapImage 。
因為我是C#編程的新手,所以請放心。
我想要的只是來自IntPtr的任何類型的位圖或圖像
提前致謝!
我想追加更多內容,但是我還不能編輯評論,因此SO自動將原始回復設為評論。 基本上看來,您的困境很常見,但是您必須考慮第三方解決方案。
要將IntPtr
為Byte[]
,我們可以使用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.