测试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

 

posted @ 2021-08-13 11:14  龙骑科技  阅读(264)  评论(0编辑  收藏  举报