【问题标题】:Memory Leak in C# when compress image压缩图像时C#中的内存泄漏
【发布时间】:2016-08-21 11:39:25
【问题描述】:

我尝试在内存中使用MagickImage 压缩ImageSource。但是它消耗了太多的内存。使用 VS 性能工具,每次调用此方法都会消耗大量内存。一旦存在,它应该需要 0Mb,对吧?

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;
                    }
                }
            }

        }
    }

【问题讨论】:

  • 当你改用return image.ToBitmapSource() 会发生什么?
  • @dlemstra 没有这样的方法
  • 您使用的是最新版本的 Magick.NET 吗?图像应该具有该方法。也许您使用的是 .NET Core 版本?

标签: c# visual-studio memory-leaks imagemagick


【解决方案1】:

由于图像是逐像素存储在内存中的。它会消耗多少内存取决于它的大小。 指定它的大小会减少很多内存。

bitmap.DecodePizelWidth = 800;

【讨论】:

    猜你喜欢
    • 2017-05-10
    • 1970-01-01
    • 2016-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多