存在将
System.Drawing.Icon
转换为 System.Media.ImageSource
的解决方案(请参阅将 System.Drawing.Icon 转换为 System.Media.ImageSource)。但是当我使用WinUI而不是WPF时,这个分辨率似乎不可用。我需要将 System.Drawing.Icon
转换为 Microsoft.UI.Xaml.ImageSource
以在 Image
控件中显示应用程序的图标。
我尝试过使用
Microsoft.UI.Xaml.Media.Imaging.BitmapSource.FromAbi(System.Drawing.Icon.Icon.Handle)
,但它抛出了System.AccessViolationException
。
那么,我怎样才能获得
Microsoft.UI.Xaml.ImageSource
版本的图标?
这是一段从 GDI+ Icon 转换为 WinUI3 BitmapSource 的 C# 代码,使用图标的像素从一个复制到另一个。
public static async Task<Microsoft.UI.Xaml.Media.Imaging.SoftwareBitmapSource> GetWinUI3BitmapSourceFromIcon(System.Drawing.Icon icon)
{
if (icon == null)
return null;
// convert to bitmap
using var bmp = icon.ToBitmap();
return await GetWinUI3BitmapSourceFromGdiBitmap(bmp);
}
public static async Task<Microsoft.UI.Xaml.Media.Imaging.SoftwareBitmapSource> GetWinUI3BitmapSourceFromGdiBitmap(System.Drawing.Bitmap bmp)
{
if (bmp == null)
return null;
// get pixels as an array of bytes
var data = bmp.LockBits(new System.Drawing.Rectangle(0, 0, bmp.Width, bmp.Height), System.Drawing.Imaging.ImageLockMode.ReadOnly, bmp.PixelFormat);
var bytes = new byte[data.Stride * data.Height];
Marshal.Copy(data.Scan0, bytes, 0, bytes.Length);
bmp.UnlockBits(data);
// get WinRT SoftwareBitmap
var softwareBitmap = new Windows.Graphics.Imaging.SoftwareBitmap(
Windows.Graphics.Imaging.BitmapPixelFormat.Bgra8,
bmp.Width,
bmp.Height,
Windows.Graphics.Imaging.BitmapAlphaMode.Premultiplied);
softwareBitmap.CopyFromBuffer(bytes.AsBuffer());
// build WinUI3 SoftwareBitmapSource
var source = new Microsoft.UI.Xaml.Media.Imaging.SoftwareBitmapSource();
await source.SetBitmapAsync(softwareBitmap);
return source;
}