C# 加载和传递图片,导致内存溢出的问题

      由C#向C++里面传递图像的过程中,多加载几次图像后,内存会暴涨,主要有两个原因:

一、pictureBox的清理不能用pictureBox.Image=null清除,而应该使用,pictureBox1.Image.Dispose()。

二、Bitmap实例化之后,需要释放用dispose()空间。

        [DllImport("HoleDetect.dll", CallingConvention = CallingConvention.Cdecl)]
        public static extern void HoleDetect(IntPtr src, int height, int width,int Stride);
        private void treeView1_NodeMouseClick_1(object sender, TreeNodeMouseClickEventArgs e)
        {
            click_node = path_dir + "\\" + e.Node.Text;
            if(pictureBox1.Image!=null)pictureBox1.Image.Dispose();
            pictureBox1.Image = Image.FromFile(click_node);

            //获取图像的指针
            Bitmap srcBmp = new Bitmap(click_node);
            int height = srcBmp.Height;
            int width = srcBmp.Width;
            BitmapData bmdata = srcBmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite,
                srcBmp.PixelFormat);
            IntPtr ptr = bmdata.Scan0; //图像指针
            HoleDetect(ptr, height, width, bmdata.Stride);
            srcBmp.UnlockBits(bmdata);
            srcBmp.Dispose();
        }if(pictureBox1.Image!=null)pictureBox1.Image.Dispose();
            pictureBox1.Image = Image.FromFile(click_node);

            //获取图像的指针
            Bitmap srcBmp = new Bitmap(click_node);
            int height = srcBmp.Height;
            int width = srcBmp.Width;
            BitmapData bmdata = srcBmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite,
                srcBmp.PixelFormat);
            IntPtr ptr = bmdata.Scan0; //图像指针
            HoleDetect(ptr, height, width, bmdata.Stride);
            srcBmp.UnlockBits(bmdata);
            srcBmp.Dispose();
        }

 

你可能感兴趣的:(C#,算法学习和研究)