2

There exist resolutions to convert System.Drawing.Icon to System.Media.ImageSource(Convert System.Drawing.Icon to System.Media.ImageSource). But when I used WinUI instead of WPF, this resolution seems to be unavailable. I need to convert System.Drawing.Icon to Microsoft.UI.Xaml.ImageSource to show icons of apps in Image control.

I have tried to use Microsoft.UI.Xaml.Media.Imaging.BitmapSource.FromAbi(System.Drawing.Icon.Icon.Handle), but it didn't work with System.AccessViolationException.

So, how can I get an Microsoft.UI.Xaml.ImageSource version of an Icon?

Jack251970
  • 39
  • 2

1 Answers1

3

Here is a C# code that convert from GDI+ Icon to WinUI3 BitmapSource, using icon's pixels copy from one to the other.

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;
}
Simon Mourier
  • 132,049
  • 21
  • 248
  • 298