【问题标题】:Image.Source property (via BitmapImage) lockes the fileImage.Source 属性(通过 BitmapImage)锁定文件
【发布时间】:2016-06-19 13:42:31
【问题描述】:

我想在我的代码中设置 image.source 属性,如下所示:

Dim bi as new BitmapImage

bi.BeginInit()
bi.UriSource = new Uri("C:/test.png", uriKind.relativeOrAbsolute)
bi.EndInit()

img.Source = bi

这行得通,但问题是这锁定了文件,使我无法替换文件。

现在我的问题是:是否有任何其他方法可以设置 image.source 属性,以便我可以在它之后说类似 file.close() 的内容?

【问题讨论】:

    标签: wpf vb.net image file locking


    【解决方案1】:

    为您的 BitmapImage 指定 BitmapCacheOption.OnLoad:

    Dim bi as new BitmapImage
    
    bi.BeginInit()
    bi.CacheOption = BitmapCacheOption.OnLoad;
    bi.UriSource = new Uri("C:/test.png", uriKind.relativeOrAbsolute)
    bi.EndInit()
    
    img.Source = bi
    

    或者您可以将图像文件内容读取到内存中的缓冲区,然后使用 MemoryStream 作为 BitmapImage 的 StreamSource:

    var imageBytes = File.ReadAllBytes("C:/test.png")
    var stream = new MemoryStream(imageBytes);
    var bi = new BitmapImage();
    
    bi.BeginInit();
    bi.StreamSource = stream;
    bi.EndInit();
    

    【讨论】:

    • bi.CacheOption = BitmapCacheOption.OnLoad 工作正常。谢谢!
    猜你喜欢
    • 2017-12-03
    • 2011-09-19
    • 2015-03-15
    • 2012-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多