图像文件副本正被另一个进程使用

Lai*_*290 5 c# wpf image file process

我正在尝试创建一个用户perfil编辑窗口,在这个窗口中有一个Image控件
当我选择一个图像文件时,它会在这个Image控件中显示并将这个文件复制到我的图像文件夹中,第一次就可以了,但是第二次,它显示错误

"该进程无法访问文件'C:\ 1.jpg',因为它正被另一个进程使用."

我认为这是因为我的Image控件正在使用这个文件,所以,我不知道我该怎么做

private void Select_Click(object sender, RoutedEventArgs e)
{
    OpenFileDialog od = new OpenFileDialog();
    if (od.ShowDialog() == true)
    {
        string imageLocal = @"C:/1.jpg";
        File.Copy(od.FileName, imageLocal, true);
        image1.Source = new BitmapImage(new Uri(imageLocal));
    }
}
Run Code Online (Sandbox Code Playgroud)

Gay*_*Fow 6

如果要加载和显示图像,并使文件适合文件系统中的操作(如重新加载或移动到另一个目录),Uri构造函数将无法工作,因为(正如您所指出的),BitmapImage类挂起文件句柄.

相反,使用这样的方法......

    private static BitmapImage ByStream(FileInfo info)
    {   //http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/dee7cb68-aca3-402b-b159-2de933f933f1
        try
        {
            if (info.Exists)
            {
                // do this so that the image file can be moved in the file system
                BitmapImage result = new BitmapImage();
                // Create new BitmapImage   
                Stream stream = new MemoryStream(); // Create new MemoryStream   
                Bitmap bitmap = new Bitmap(info.FullName);
                // Create new Bitmap (System.Drawing.Bitmap) from the existing image file 
                                             (albumArtSource set to its path name)   
                bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                // Save the loaded Bitmap into the MemoryStream - Png format was the only one I 
                              tried that didn't cause an error (tried Jpg, Bmp, MemoryBmp)   
                bitmap.Dispose(); // Dispose bitmap so it releases the source image file   
                result.BeginInit(); // Begin the BitmapImage's initialisation   
                result.StreamSource = stream;
                // Set the BitmapImage's StreamSource to the MemoryStream containing the image   
                result.EndInit(); // End the BitmapImage's initialisation   
                return result; // Finally, set the WPF Image component's source to the 
                                BitmapImage  
            }
            return null;
        }
        catch
        {
            return null;
        }
    }
Run Code Online (Sandbox Code Playgroud)

此方法接受FileInfo并返回可以显示的BitmapImage,同时将其移动到另一个目录或再次显示.

从下面的另一个答案复制的一个更简单的方法是:

public static BitmapImage LoadBitmapImage(string fileName)
{
    using (var stream = new FileStream(fileName, FileMode.Open))
    {
        var bitmapImage = new BitmapImage();
        bitmapImage.BeginInit();
        bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
        bitmapImage.StreamSource = stream;
        bitmapImage.EndInit();
        bitmapImage.Freeze(); 
        return bitmapImage;
    }
}
Run Code Online (Sandbox Code Playgroud)