Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#从使用中释放图像文件_C#_Image_Bmp - Fatal编程技术网

C#从使用中释放图像文件

C#从使用中释放图像文件,c#,image,bmp,C#,Image,Bmp,我有一个临时图像文件,我用它打开 Bitmap CapturedImg = (Bitmap)Image.FromFile("Item/Item.bmp"); 因为是temp,我想用另一个图像替换它以供进一步使用,但程序仍在使用该图像,我无能为力 如何从图像中释放以便替换?尝试使用此语法 using (Bitmap bmp = (Bitmap)Image.FromFile("Item/Item.bmp")) { // Do here everything you need with th

我有一个临时图像文件,我用它打开

Bitmap CapturedImg = (Bitmap)Image.FromFile("Item/Item.bmp");
因为是temp,我想用另一个图像替换它以供进一步使用,但程序仍在使用该图像,我无能为力

如何从图像中释放以便替换?

尝试使用此语法

using (Bitmap bmp = (Bitmap)Image.FromFile("Item/Item.bmp"))
{
    // Do here everything you need with the image
}
// Exiting the block, image will be disposed
// so you should be free to delete or replace it

在释放图像之前,文件将保持锁定状态

改为从文件流读取图像

using( FileStream stream = new FileStream( path, FileMode.Open, FileAccess.Read ) )
{
         image = Image.FromStream( stream );
}

我遇到了类似的问题,无法使用using,因为该文件被一些异步代码覆盖。我通过复制位图并释放原始位图解决了此问题:

                Bitmap tmpBmp = new Bitmap(fullfilename);
                Bitmap image= new Bitmap(tmpBmp);
                tmpBmp.Dispose();
你也可以试试这个

 BitmapImage bmpImage= new BitmapImage();
 bmpImage.BeginInit();
 Uri uri = new Uri(fileLocation);
 bmpImage.UriSource = uri;
 bmpImage.CacheOption = BitmapCacheOption.OnLoad;
 bmpImage.EndInit();
 return bmpImage;
这就像:

public Bitmap OpenImage(string filePath) =>
    return new Bitmap(filePath).Clone();
或者像这样:

public Bitmap OpenImage(string filePath)
{
    using (Bitmap tmpBmp = (Bitmap)Image.FromFile(filePath))
    {
        return new Bitmap(tmpBmp);
    }
}
public Bitmap OpenImage(string filePath)
{
    using (var stream = System.IO.File.OpenRead(filePath))
    {
        return (Bitmap)System.Drawing.Image.FromStream(stream);
    }
}
或者像这样:

public Bitmap OpenImage(string filePath)
{
    using (Bitmap tmpBmp = (Bitmap)Image.FromFile(filePath))
    {
        return new Bitmap(tmpBmp);
    }
}
public Bitmap OpenImage(string filePath)
{
    using (var stream = System.IO.File.OpenRead(filePath))
    {
        return (Bitmap)System.Drawing.Image.FromStream(stream);
    }
}

位图CapturedImg=(位图)Image.FromFile(“Item/NewItem.bmp”);如果在加载图像后将其添加到picturebox中,请尝试保存并处置CapturedImg,然后再将其替换为新的CapturedImg。请尝试PictureBox1.Refresh();我认为这可能更容易
Bitmap image=new Bitmap(fullfilename).Clone()