美文网首页
WPF BitmapImage 占用文件资源无法释放问题

WPF BitmapImage 占用文件资源无法释放问题

作者: 虫虫侠教育 | 来源:发表于2019-02-21 08:23 被阅读0次

相关:http://blog.sina.com.cn/s/blog_3f2c72ea0100srdg.html

场景:

WPF下用Image控件展示图片;

控件的图片源自然选用BitmapImage; 

BitmapImage通过Uri对象指向磁盘的某个文件。

显示正常,但是这时候如果我们再有别的地方要操作这个磁盘文件,比如程序中或者其他地方,就会说资源已被占用。

资源无法释放的加载方式为:

_selectedColor = "/Image/pencil_strokes.png";

ImageSource imageSource = new BitmapImage(new Uri(_selectedColor));

解决方案:

ImageSource imageSource = AppHelper.GetBitmapImage(new Uri(Path.GetDirectoryName(Application.ResourceAssembly.Location) + @_selectedColor, UriKind.Absolute).AbsolutePath);

public static BitmapImage GetBitmapImage(string imagePath)

        {

            BitmapImage bitmap = new BitmapImage();

            if (File.Exists(imagePath))

            {

                bitmap.BeginInit();

                bitmap.CacheOption = BitmapCacheOption.OnLoad;

                using (Stream ms = new MemoryStream(File.ReadAllBytes(imagePath)))

                {

                    bitmap.StreamSource = ms;

                    bitmap.EndInit();

                    bitmap.Freeze();

                }

            }

            return bitmap;

        }

相关文章

网友评论

      本文标题:WPF BitmapImage 占用文件资源无法释放问题

      本文链接:https://www.haomeiwen.com/subject/ulplyqtx.html