1. 程式人生 > 其它 >測試Bitmap和Marshal.Copy

測試Bitmap和Marshal.Copy

Bitmap Marshal.Copy 託管記憶體 非託管記憶體
 #region 測試Bitmap和Marshal.Copy
        public static void TestBitmapAndMarshalCopy()
        {
            //測試Bitmap和Marshal.Copy
            Bitmap bitmap1 = new Bitmap("./123456.jpg");
            Rectangle rectangle = new Rectangle(0, 0, bitmap1.Width, bitmap1.Height);
            //鎖定bitmap到系統記憶體
            System.Drawing.Imaging.BitmapData bitmapData = bitmap1.LockBits(rectangle, System.Drawing.Imaging.ImageLockMode.ReadWrite, bitmap1.PixelFormat);
            
//BitmapData 指定 Bitmap 的特性,如大小、畫素格式、畫素資料在記憶體中的起始地址以及每個掃描行的長度(步幅)。 var pixel = bitmapData.PixelFormat; //Bitmap 的特性 寬度 var Width = bitmapData.Width;//Bitmap 的特性 寬度 var Height = bitmapData.Height; //Bitmap 的特性 高度 var firstStartAddress = bitmapData.Scan0;//畫素資料在記憶體中的起始地址
var Stride = bitmapData.Stride;//畫素資料在記憶體中的每個掃描行的長度(步幅) var leength = Math.Abs(bitmapData.Stride) * bitmapData.Height; byte[] bts = new byte[leength]; // 將資料從非託管記憶體指標複製到託管 8 位無符號整數陣列 System.Runtime.InteropServices.Marshal.Copy(firstStartAddress, bts, 0
, bts.Length); //使rgb圖片變紅色 for (int i = 2; i < bts.Length; i += 3) { bts[i] = 255; } //將資料從一維託管 8 位無符號整數陣列複製到非託管記憶體指標。 System.Runtime.InteropServices.Marshal.Copy(bts, 0, firstStartAddress, bts.Length); bitmap1.UnlockBits(bitmapData); bitmap1.Save("./123456new.jpg", System.Drawing.Imaging.ImageFormat.Jpeg); bitmap1.Dispose(); //測試託管記憶體到非託管記憶體 string a = "123456"; IntPtr dd = System.Runtime.InteropServices.Marshal.AllocHGlobal(10); char[] chars = a.ToCharArray(); // 將資料從一維託管字元陣列複製到非託管記憶體指標。 System.Runtime.InteropServices.Marshal.Copy(chars, 0, dd, chars.Length); //修改 // char[] chars1 = new char[chars.Length]; //將資料從非託管記憶體指標複製到託管字元陣列。 System.Runtime.InteropServices.Marshal.Copy(dd, chars1, 0, chars.Length); System.Runtime.InteropServices.Marshal.FreeHGlobal(dd); } #endregion
龍騰一族至尊龍騎