Load a BitmapSource and save using the same name in WPF -gt; IOException(加载一个 BitmapSource 并在 WPF 中使用相同的名称保存 -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();
}
这篇关于加载一个 BitmapSource 并在 WPF 中使用相同的名称保存 ->IO异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:加载一个 BitmapSource 并在 WPF 中使用相同的名称保


- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- 使用 rss + c# 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01