1. 程式人生 > >C# 載入和傳遞圖片,導致記憶體溢位的問題

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