Load a BitmapSource and save using the same name in WPF -gt; IOException(在 WPF 中加载 BitmapSource 并使用相同的名称保存 -IO异常)
问题描述
当我尝试保存之前加载的 BitmapSource 时,抛出 System.IO.IOException 说明另一个进程正在访问该文件并且无法打开文件流.
When I try to save a BitmapSource that I loaded earlier, a System.IO.IOException is thrown stating another process is accessing that file and the filestream cannot be opened.
如果我只保存而不提前加载,一切正常.
If I only save whithout loading earlier, everything works fine.
加载代码:
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);
}
加载图像数据后,文件似乎仍然被锁定,并且在打开它的应用程序仍在运行时永远无法覆盖.任何想法如何解决这个问题?非常感谢任何解决方案.
It seems like after loading the image data, the file is still locked an can never be overwritten while the application who opened it is still running. Any ideas how to solve this? Thanks alot for any solutions.
推荐答案
受我对这个问题的评论的启发,我通过将所有字节读入内存流并将其用作 BitmapImage 的 Sreamsource 来解决问题.
Inspired by the comments I got on this issue, I solved the problem by reading all bytes into a memorystream and using it as the BitmapImage's 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();
}
这篇关于在 WPF 中加载 BitmapSource 并使用相同的名称保存 ->IO异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 WPF 中加载 BitmapSource 并使用相同的名称保存 ->IO异常
基础教程推荐
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
