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()代码>