问题
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