1. 程式人生 > >c# 使用bitmapimage載入圖片佔用資源,刪除時報無法刪除,資源被佔用。

c# 使用bitmapimage載入圖片佔用資源,刪除時報無法刪除,資源被佔用。

        查資料後決定修改為流的方式載入圖片:如下,
        System.IO.MemoryStream ms = new System.IO.MemoryStream();

        Image myImage3 = new Image();
        BitmapImage bi3 = new BitmapImage();
        bi3.BeginInit();

        bi3.StreamSource = ms;  //將流物件給StreamSource

        bi3.EndInit();
        myImage3.Stretch = Stretch.Fill;
        myImage3.Source = bi3;

public static BitmapImage GetImage(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;

兩段程式碼摘取要用的合併,OK。