【问题标题】:Image.Source from Bitmap not being showed [duplicate]未显示来自位图的 Image.Source [重复]
【发布时间】:2014-09-14 11:06:10
【问题描述】:

我有一个存储一些图像的位图列表。然后我希望 WPF UserControl 上的 Image 元素成为该列表的第一个元素。为此,我尝试了这个:

Image2.Source = myBitmapArray[0].ToBitmapImage();

其中ToBitmapImage 是一个静态函数,如下所示:

public static BitmapImage ToBitmapImage(this Bitmap bitmap)
    {
        BitmapImage bitmapImage = new BitmapImage();

        using (MemoryStream memoryStream = new MemoryStream())
        {
            bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Bmp);
            memoryStream.Position = 0;
            bitmapImage.BeginInit();
            bitmapImage.StreamSource = memoryStream;
            bitmapImage.EndInit();
        }

        return bitmapImage;
    }

但是当我将BitmapImage 分配给我的Image.Source 时,它不会显示图像。我做错了什么?

【问题讨论】:

    标签: c# .net wpf image


    【解决方案1】:

    在将MemoryStream 分配给StreamSource 属性后,您正在处理它。

    但是根据BitmapImage.StreamSource你必须

    如果您希望在创建 BitmapImage 后关闭流,请将 CacheOption 属性设置为 BitmapCacheOption.OnLoad。默认的 OnDemand 缓存选项保留对流的访问,直到需要位图,并且清理由垃圾收集器处理。

    所以要么删除using 语句,这样MemoryStream 就不会被释放,或者使用BitmapCacheOption.OnLoad

    【讨论】:

    • 太棒了!真是个错误……现在可以了。谢谢! (7 分钟接受您的回答)
    猜你喜欢
    • 1970-01-01
    • 2013-12-31
    • 2014-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多