2016-04-27 31 views
3

我嘗試在內存中壓縮ImageSourceMagickImage。但它消耗太多內存。使用VS性能工具,每次調用此方法都會消耗大量內存。它一旦存在就應該消耗0Mb,對吧?壓縮映像時C#中的內存泄漏

internal static System.Windows.Media.ImageSource compressImage(System.Windows.Media.ImageSource ims) 
     { 
      using (MemoryStream stream = new MemoryStream()) 
      { 
       using (MemoryStream outS = new MemoryStream()) 
       { 
        BitmapSource bs = ims as BitmapSource; 
        JpegBitmapEncoder encoder = new JpegBitmapEncoder(); 
        BitmapFrame bf = BitmapFrame.Create(bs); 
        //encoder.Frames.Add(BitmapFrame.Create(image1.Source)); 
        encoder.Frames.Add(bf); 
        encoder.Save(stream); 
        stream.Flush(); 

        try 
        { 
         // Read first frame of gif image 
         using (MagickImage image = new MagickImage(stream)) 
         { 
          image.Quality = 75; 
          image.Resize(new Percentage(0.65)); 
          image.Density = new Density(200, DensityUnit.PixelsPerInch); 
          image.Write(outS); 
         } 

         stream.Close(); 
         BitmapImage bitmap = new BitmapImage(); 
         bitmap.BeginInit(); 
         bitmap.CacheOption = BitmapCacheOption.OnLoad; 
         outS.Position = 0; 
         bitmap.StreamSource = outS; 
         // 
         bitmap.EndInit(); 
         //bitmap.Freeze(); 
         outS.Flush(); 
         outS.Close(); 
         ims = null; 
         return bitmap; 
        } 
        catch (Exception e) 
        { 
         return null; 
        } 
       } 
      } 

     } 
    } 
+0

當你使用'return image.ToBitmapSource()'時,會發生什麼? – dlemstra

+0

@dlemstra沒有這樣的方法 – Xiaokun

+1

您使用的是最新版本的Magick.NET嗎?圖像應該有這種方法。也許你正在使用.NET Core版本? – dlemstra

回答

0

由於圖像以像素爲單位存儲在內存中。它會消耗大量的內存,取決於它的大小。 指定其大小將減少很多內存。

bitmap.DecodePizelWidth = 800;