How to convert icon (Bitmap) to ImageSource?

后端 未结 2 1914
猫巷女王i
猫巷女王i 2020-12-20 19:52

I have a button and an image named as image1 in my wpf app. I want add image source of the image1 from a file icon of a location or file path. Here is my code:



        
2条回答
  •  天命终不由人
    2020-12-20 20:36

    The error you get is because you try to assign a bitmap as the source of an image. To rectify that, use this function:

    BitmapImage BitmapToImageSource(Bitmap bitmap)
    {
        using (MemoryStream memory = new MemoryStream())
        {
            bitmap.Save(memory, System.Drawing.Imaging.ImageFormat.Bmp);
            memory.Position = 0;
            BitmapImage bitmapimage = new BitmapImage();
            bitmapimage.BeginInit();
            bitmapimage.StreamSource = memory;
            bitmapimage.CacheOption = BitmapCacheOption.OnLoad;
            bitmapimage.EndInit();
    
            return bitmapimage;
        }
    }
    

    like this:

    image1.Source = BitmapToImageSource(ico.ToBitmap());
    

提交回复
热议问题