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# - 如何使用绑定(bind)绑定(bind)资源目录源属性

c# - WPF中如何根据数据库查询创建按钮

javascript - 将 html 链接加载到 div 中

r - 在 R 中保存并重新加载 'list' 对象

jquery - $(this) 在函数中不起作用

c# - 重新保存Blazor WASM的.razor文件

c# - 请求 Expression<Func<T, decimal>> 时防止隐式转换为 int

c# - 如何为 COM Interop 库而不是程序集生成 C# 源代码?

c# - MarshalAsAttribute Sizeconst .NET

wpf - 如何在 CheckedComboBoxEdit 中获取选定项?