如何在WPF(C#)中清除图像控件
我在我的C驱动器中有一个带有源图像的图像控件.每当我尝试删除原始图像以将其动态更改为另一图像时,都会收到一条消息,指出该图像正被另一进程使用.如何从图像控件释放图像以将其删除.
我尝试了以下变体:
I have an image control with a source image located in my c drive. I get a message that the image is being used by another process whenever I try to delete the original image to change it with another one dynamically. How do I release the image from the image control to be able to delete it.
I tried this variants:
string path = ((BitmapImage)img.Source).UriSource.LocalPath;
img.SetValue(System.Windows.Controls.Image.SourceProperty, null);
File.Delete(path);
并且:
And:
string path = ((BitmapImage)img.Source).UriSource.LocalPath;
img.Source = null;
File.Delete(path)
但这不行...
调用DeleteImage方法时,此代码会产生以下错误:
该进程无法访问文件"C:\ Picther.jpg",因为该文件正在被另一个进程使用.
But it''s not work...
This code produces the following error when the DeleteImage method is called:
The process cannot access the file ''C:\Picther.jpg'' because it is being used by another process.
您好,
实现这一点有些棘手,因为ImageControl无法处理BitmapImage中的BitmapStream.
BitmapCacheOption.OnLoad属性解决了此问题,如下所示:
Hi,
it''s a bit tricky to achieve this because BitmapStream from BitmapImage couldn''t be disposed by ImageControl.
BitmapCacheOption.OnLoad Property solves this problem, like this:
public MainWindow()
{
InitializeComponent();
//Display your image in Image Control
image1.Source = BitmapFromUri(new Uri(@"c:\test.jpg"));
}
private void button_DEL_Image_Click(object sender, RoutedEventArgs e)
{
image1.Source = null;
File.Delete(@"c:\test.jpg");
}
public static ImageSource BitmapFromUri(Uri source)
{
var bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.UriSource = source;
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.EndInit();
return bitmap;
}
问候
Regards
你好
试试这个:
Hello
Try this:
img.Source = null;
(new System.Threading.Thread(() =>
{
while (true)
{
try
{
File.Delete(path);
MessageBox.Show("Picture Removed");
break;
}
catch{}
}
})).Start();
您可以在尝试删除时显示一个ProgressBar,即显示:请等待删除文件..."
You can show a ProgressBar while tring to remove, that is showing: "Please wait to remove the file..."
这是我发现的另一种将图像加载到内存中并使用的方法作为图像来源:
Here is another way I found to load an image into memory and use it as an image source:
BitmapImage image = new BitmapImage();
image.BeginInit();
Uri imageSource=new Uri("file://"+ "C:/temp/FoxLogo.png");
image.UriSource = imageSource;
image.EndInit();
img.Source = image;