OutOfMemoryException读取WPF中的MemoryStream [英] OutOfMemoryException reading MemoryStream in WPF

查看:84
本文介绍了OutOfMemoryException读取WPF中的MemoryStream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我有一个WPF应用程序,我需要将"Windows.System.Media.Imageing.BitmapImage"对象的数组转换为"System.Drawing.Image"对象的数组.以下方法在大多数情况下都可以正常工作,但是有时会引发"OutOfMemoryException",可能与较大的图像数组有关.

这些方法是静态类的一部分.

从流中读取时,在"ConvertImage"的第三行到最后一行引发异常.

Hi,
I have a WPF application where I need to convert an array of "Windows.System.Media.Imageing.BitmapImage" objects to an array of "System.Drawing.Image" objects. The following methods work well most of the time but an "OutOfMemoryException" is sometimes raised, possibly with larger image arrays.

These methods are part of a static class.

The exception is raised on the third to last line of "ConvertImage" when it reads from the stream.

private static System.Drawing.Image[] ConvertImageArray(BitmapImage[] bmpThePages)
        {
            System.Drawing.Image[] sdiThePages = new System.Drawing.Image[bmpThePages.Length];

            for (int x = 0; x < bmpThePages.Length; x++)
            {
                ConvertImage(ref bmpThePages[x], ref sdiThePages[x]);
            }

            return sdiThePages;
        }

        private static void ConvertImage(ref BitmapImage bmpThePage,ref System.Drawing.Image sdiThePage)
        {
            MemoryStream ms = new MemoryStream();
            TiffBitmapEncoder encoder = new TiffBitmapEncoder();
            encoder.Frames.Add(BitmapFrame.Create(bmpThePage));
            encoder.Save(ms);

            sdiThePage = System.Drawing.Image.FromStream(ms);

            ms.Close();//redundant
            ms.Dispose();
}

推荐答案

小修正:

Small correction:

private static System.Drawing.Image ConvertImage(BitmapImage bmpThePage)
{
   using (MemoryStream ms = new MemoryStream()) {
        TiffBitmapEncoder encoder = new TiffBitmapEncoder();
        encoder.Frames.Add(BitmapFrame.Create(bmpThePage));
        encoder.Save(ms);
        return System.Drawing.Image.FromStream(ms);
   } //ms is disposed here 
}



您不需要ref的参数.输入参数为引用类型,另一个应为返回值.另外,我使用了using构造来自动配置内存流.在这种情况下,即使在异常情况下也会调用Dispose(您应始终使用此技术来初始化实现IDisposable的任何类的实例).

—SA



You don''t need parameters by ref. Input parameter is of reference type, and another one should be a return value. Also, I used using construct to dispose memory stream automatically. In this case Dispose will be called even on exception (you should always use this technique to initialize an instance of any class implementing IDisposable).

—SA


这篇关于OutOfMemoryException读取WPF中的MemoryStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆