使用C#免费图像文件
我有一个临时图像文件,我打开
Bitmap CapturedImg = (Bitmap)Image.FromFile("Item/Item.bmp");
因为是临时我想用另一个图像替换它以供进一步使用,但程序仍然使用该图像,我无法做任何事情。
如何放弃图像才能被替换?
我有一个类似的问题,无法使用,因为该文件被一些异步代码覆盖。 我通过复制Bitmap并释放原始Bitmap解决了这个问题:
Bitmap tmpBmp = new Bitmap(fullfilename); Bitmap image= new Bitmap(tmpBmp); tmpBmp.Dispose();
来自MSDN
文件保持锁定状态,直到图像被丢弃。
从文件流中读取图像
using( FileStream stream = new FileStream( path, FileMode.Open, FileAccess.Read ) ) { image = Image.FromStream( stream ); }
尝试使用此语法
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 (var stream = System.IO.File.OpenRead("Item\Item.bmp")) { var image= (Bitmap)System.Drawing.Image.FromStream(stream) }
你也可以试试这个。
BitmapImage bmpImage= new BitmapImage(); bmpImage.BeginInit(); Uri uri = new Uri(fileLocation); bmpImage.UriSource = uri; bmpImage.CacheOption = BitmapCacheOption.OnLoad; bmpImage.EndInit(); return bmpImage;