c# - 加载 BitmapSource 并在 WPF -> IOException 中使用相同的名称保存

标签 c# wpf load bitmap save

当我尝试保存我之前加载的 BitmapSource 时,抛出 System.IO.IOException 说明另一个进程正在访问该文件并且无法打开文件流。

如果我只保存而不提前加载,一切正常。

加载代码:

BitmapImage image = new BitmapImage();

image.BeginInit();
image.UriSource = uri;

if (decodePixelWidth > 0)
image.DecodePixelWidth = decodePixelWidth;

image.EndInit();

保存代码:

using (FileStream fileStream = new FileStream(Directory + "\\" + FileName + ".jpg", FileMode.Create))
{
    JpegBitmapEncoder encoder = new JpegBitmapEncoder();
    encoder.Frames.Add(BitmapFrame.Create((BitmapImage)image));
    encoder.QualityLevel = 100;
    encoder.Save(fileStream);
}

似乎在加载图像数据后,文件仍然被锁定并且在打开它的应用程序仍在运行时永远无法被覆盖。任何想法如何解决这个问题?非常感谢任何解决方案。

最佳答案

受我对这个问题的评论的启发,我通过将所有字节读入内存流并将其用作 BitmapImage 的 Sreamsource 解决了这个问题。

这个很完美:

if (File.Exists(filePath))
{
    MemoryStream memoryStream = new MemoryStream();

    byte[] fileBytes = File.ReadAllBytes(filePath);
    memoryStream.Write(fileBytes, 0, fileBytes.Length);
    memoryStream.Position = 0;

    image.BeginInit();
    image.StreamSource = memoryStream;

    if (decodePixelWidth > 0)
        image.DecodePixelWidth = decodePixelWidth;

    image.EndInit();
}

关于c# - 加载 BitmapSource 并在 WPF -> IOException 中使用相同的名称保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/542217/

相关文章:

c# - 保持前端 Angular 5 和后端 Web API 代码分离的简单方法?

c# - 为什么我们不能在 C# 中进行 IntPtr 和 UIntPtr 运算?

wpf - XAML:获取父背景

ios - 完成 Web 服务调用后加载屏幕

Mysql 跳过 LOAD DATA INFILE 中的行

c# - 带有响应式扩展的命名管道

c# - 对象属性在列表中重复多少次

wpf - CollectionViewSource View 绑定(bind)不适用于自定义控件

c# - 在 XAML 中找不到 WPF 类

Jquery:如何检查新打开的窗口是否已完全加载?/window 加载外部页面(如 www.yahoo.com)