2

我编写了一个应用程序,它从操作系统获取文件图标并绑定到它们,但由于System.Drawing.Icon对象不能用作Image控件中的ImageSource,我不得不编写一个转换器

经过一番搜索后,我得到了以下代码,我目前正在使用它:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
    Icon ico = (value as Icon);
    Bitmap bits = ico.ToBitmap();
    MemoryStream strm = new MemoryStream();

    // add the stream to the image streams collection so we can get rid of it later
    _imageStreams.Add(strm);
    bits.Save(strm, System.Drawing.Imaging.ImageFormat.Png);
    BitmapImage bitmap = new BitmapImage();
    bitmap.BeginInit();
    bitmap.StreamSource = strm;
    bitmap.EndInit();

    // freeze it here for performance
    bitmap.Freeze();
    return bitmap;
}

我有三个问题:

  1. 您可以提出更好的解决方案吗?

  2. 最终关闭使用的MemoryStreams 的最佳方法是什么,因为这里的代码是由绑定系统自动调用的?(它们从不手动实例化,您可能会注意到我将流添加到集合中Close(),在析构函数中调用它们,但我认为这不是一个好的解决方案)。

  3. 与上一个问题相关,当我尝试在函数结束之前关闭流时,即使在此之前调用Stream.Flush() ,图像也会显示为空。为什么是这样?

4

1 回答 1

0

我最近在尝试将我的项目资源 (WindowIcon) 中的图标分配给 Window.Icon ImageSource 时取得了以下成功:

using System.Drawing;
using System.Windows.Media;

...

Icon someIcon = Properties.Resources.WindowIcon;
Bitmap someBitmap = someIcon.ToBitmap();
this.Icon = (ImageSource)new ImageSourceConverter().ConvertFrom(someBitmap);
于 2013-08-22T10:14:01.347 回答