Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you convert a System.Windows.Control.Image to a System.Drawing.Icon?

Tags:

c#

image

wpf

The title of the question pretty much states the problem. Is it possible?

like image 671
Mark Schroering Avatar asked Jan 24 '23 06:01

Mark Schroering


2 Answers

As an alternative, I've used the hints found here:

public static Icon Convert(BitmapImage bitmapImage)
{
    var ms = new MemoryStream();
    var encoder = new PngBitmapEncoder(); // With this we also respect transparency.
    encoder.Frames.Add(BitmapFrame.Create(bitmapImage));
    encoder.Save(ms);

    var bmp = new Bitmap(ms);
    return Icon.FromHandle(bmp.GetHicon());
}
like image 66
Daniel Rose Avatar answered Jan 30 '23 12:01

Daniel Rose


I modified an example from here. This seems to work pretty good.

    public static Icon Convert(BitmapImage bitmapImage)
    {
        System.Drawing.Bitmap bitmap = null;
        var width = bitmapImage.PixelWidth;
        var height = bitmapImage.PixelHeight;
        var stride = width * ((bitmapImage.Format.BitsPerPixel + 7) / 8);

        var bits = new byte[height * stride];

        bitmapImage.CopyPixels(bits, stride, 0);

        unsafe
        {
            fixed (byte* pB = bits)
            {
                var ptr = new IntPtr(pB);

                bitmap = new System.Drawing.Bitmap(width, height, stride,
                                                System.Drawing.Imaging.PixelFormat.Format32bppPArgb,
                                                ptr);
            }

        }

        return Icon.FromHandle(bitmap.GetHicon());
    }
like image 33
Mark Schroering Avatar answered Jan 30 '23 13:01

Mark Schroering