我正在尝试将所选图像复制到文件夹,然后要与Image对象一起显示。复制工作正常,但是当我要显示它时,似乎程序找不到它。仅当我手动使用“添加现有项”时,才显示图像。有没有办法自动添加它?
这是我的代码:
string name = "image1";
OpenFileDialog dialog = new OpenFileDialog();
Nullable<bool> dialogOK = dialog.ShowDialog();
if(dialogOK == true)
{
File.Copy(dialog.FileName, @"..\..\Images\" + name + ".png", true);
image.Source = new BitmapImage(new Uri(@"Images\" + name + ".png", UriKind.Relative));
}
(“图像”在xaml中定义)
使用绝对路径加载BitmapImage似乎更安全:
var dialog = new OpenFileDialog();
if (dialog.ShowDialog() == true)
{
var targetFile = @"..\..\Images\" + name + ".png";
var currentDir = Environment.CurrentDirectory;
var targetPath = Path.Combine(currentDir, targetFile);
var targetDir = Path.GetDirectoryName(targetPath);
Directory.CreateDirectory(targetDir);
File.Copy(dialog.FileName, targetPath, true);
image.Source = new BitmapImage(new Uri(targetPath));
}
为了在加载BitmapImage之后直接释放文件,请从FileStream加载它:
BitmapImage bitmap = new BitmapImage();
using (var stream = File.OpenRead(targetPath))
{
bitmap.BeginInit();
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.StreamSource = stream;
bitmap.EndInit();
}
image.Source = bitmap;