C# Free Image file from use

拟墨画扇 提交于 2019-12-23 13:05:30

问题


i have a temp image file which i open with

Bitmap CapturedImg = (Bitmap)Image.FromFile("Item/Item.bmp");

and because is temp i want to replace it with another image for further use, but the program still using that image and i cannot do anything.

How to let go from the image in order to be replaced?


回答1:


I had a similar problem and could not use using, since the file was overwritten by some asynchronous code. I solved the issue by making a copy of the Bitmap and freeing the original one:

                Bitmap tmpBmp = new Bitmap(fullfilename);
                Bitmap image= new Bitmap(tmpBmp);
                tmpBmp.Dispose();



回答2:


From MSDN

The file remains locked until the Image is disposed.

Read Image from File Stream Instead

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



回答3:


Try using this syntax

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



回答4:


using (var stream = System.IO.File.OpenRead("Item\Item.bmp"))
{
    var image= (Bitmap)System.Drawing.Image.FromStream(stream)
}



回答5:


You can also try this.

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



回答6:


This like:

public Bitmap OpenImage(string filePath) =>
    return new Bitmap(filePath).Clone();

Or this like:

public Bitmap OpenImage(string filePath)
{
    using (Bitmap tmpBmp = (Bitmap)Image.FromFile(filePath))
    {
        return new Bitmap(tmpBmp);
    }
}

Or this like:

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


来源:https://stackoverflow.com/questions/11408857/c-sharp-free-image-file-from-use

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!