簡體   English   中英

將 System.Drawing.Bitmap 轉換為 Windows.Graphics.Imaging.SoftwareBitmap

[英]Convert a System.Drawing.Bitmap to Windows.Graphics.Imaging.SoftwareBitmap

我有一個 WPF 項目,並將圖像從 usb 相機捕獲到 System.Drawing.Bitmap(我也可以捕獲 System.Windows.Media.Imaging.BitmapSource)並需要將其轉換為 Windows.GraphicsSoftware.Bitmaping 到。制作一個“VideoFrame”以與 Onnx model 進行比較。

相機驅動程序是一個 .net 程序集,不會綁定到 uwp 項目。 我嘗試創建一個 .net 標准程序集來彌合差距,但沒有成功。 我只需要將 bitmap 轉換為 SoftwareBitmap。 請幫忙!

我使用此代碼是基於對來自相機的 Bitmap 圖像的同情 - https://github.com/Azure-Samples/cognitive-services-onnx12-customvision-sample

沒有直接轉換。 您需要從System.Drawing.Bitmap中提取圖像數據,然后根據該數據創建新的SoftwareBitmap。

例如,您可以使用Save(Stream,ImageFormat)方法將此圖像以指定格式保存到指定流。

然后,您可以嘗試調用BitmapDecoder.CreateAsync方法從流中創建解碼器。

之后,您可以調用GetSoftwareBitmapAsync來獲取SoftwareBitmap對象。

以下是一個簡單的代碼示例:

Bitmap bitmap = getyourbitmap();
using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
{
    bitmap.Save(stream.AsStream(),ImageFormat.Jpeg);//choose the specific image format by your own bitmap source
    Windows.Graphics.Imaging.BitmapDecoder decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(stream);
    SoftwareBitmap softwareBitmap = await decoder.GetSoftwareBitmapAsync();
}

我發現您可以使用Windows.Security.Cryptography從圖像數組字節創建IBuffer。 然后,您可以將IBuffer復制到SoftwareBitmap。

using Windows.Security.Cryptography;

IBuffer buffer = CryptographicBuffer.CreateFromByteArray(ImageByteArray);

SoftwareBitmap softwareBitmap = new SoftwareBitmap(BitmapPixelFormat.Gray8, 800, 600);
softwareBitmap.CopyFromBuffer(buffer);
VideoFrame inputImage = VideoFrame.CreateWithSoftwareBitmap(softwareBitmap);

這對我有用:

Bitmap bitmap = ...;
var memoryStream = new MemoryStream();
using (var graphics = Graphics.FromImage(bitmap))
{
    bitmap.Save(memoryStream, ImageFormat.Bmp);
}

var decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(stream);
var bitmap = await decoder.GetSoftwareBitmapAsync();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM