Deleting a window's background image WPF

夙愿已清 提交于 2019-12-05 22:14:57

The answer Thomas gave is correct, and works well if you have a file path, don't want to cache the bitmap, and don't want to use XAML.

However it should also be mentioned that BitmapImage has a built-in way to load the bitmap immediately by setting BitmapCacheOption:

BitmapImage img = new BitmapImage { CacheOption = BitmapCacheOption.OnLoad };
img.BeginInit();
img.UriSource = imageUrl;
img.EndInit();

or

<BitmapImage CacheOption="OnLoad" UriSource="..." />

This will load the bitmap immediately and explicitly close the stream, just as using a FileStream would, but with several differences:

  • It will work with any Uri, such as a pack:// Uri.
  • It can be used directly from XAML
  • The bitmap is cached in the bitmap cache, so future use of the same Uri won't go to the disk. In your particular application this may be a bad thing, but for other uses it may be a desirable feature.

I assume you're loading the image directly from the file, like that ?

BitmapImage img = new BitmapImage();
img.BeginInit();
img.UriSource = imageUrl;
img.EndInit();

Try to load it from a stream instead ; that way you can close the stream yourself after the image is loaded, so that the file isn't locked :

BitmapImage img = new BitmapImage();
using (FileStream fs = File.OpenRead(imageFilePath)
{
    img.BeginInit();
    img.StreamSource = fs;
    img.EndInit();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!