C#免费图像文件使用

问题描述 投票:4回答:6

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

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

因为是临时我想用另一个图像替换它以供进一步使用,但程序仍然使用该图像,我无法做任何事情。

如何放弃图像才能被替换?

c# image bmp
6个回答
2
投票

我有一个类似的问题,无法使用,因为该文件被一些异步代码覆盖。我通过复制Bitmap并释放原始Bitmap解决了这个问题:

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

2
投票

来自MSDN

文件保持锁定状态,直到图像被丢弃。

从文件流中读取图像

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

1
投票

尝试使用此语法

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

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

0
投票

你也可以试试这个。

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

0
投票

这像:

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);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.