加载的BitmapSource并保存在WPF中使用相同的名称 - > IOException异常 [英] Load a BitmapSource and save using the same name in WPF -> IOException

查看:192
本文介绍了加载的BitmapSource并保存在WPF中使用相同的名称 - > IOException异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试保存我前面加载的BitmapSource,一个 System.IO.IOException 被抛出,说明另一个进程正在访问的文件和FILESTREAM无法打开。

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.

加载code:

BitmapImage image = new BitmapImage();

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

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

image.EndInit();

保存code:

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.

推荐答案

由我在​​这个问题上有意见的启发,我读的所有字节到MemoryStream并使用它作为的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中使用相同的名称 - > IOException异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆