C# Bitmap 处理

本文介绍了三种不同的位图深拷贝方法:使用锁位、绘图API和句柄对象来实现位图的完全复制。这些方法适用于不同场景,帮助开发者有效避免因位图共享导致的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


        /// <summary>
        /// 拷贝
        /// </summary>
        /// <param name="bitmap"></param>
        /// <returns></returns>
        private Bitmap DeepCopyBitmap(Bitmap bitmap)
        {
            //Stopwatch watch = Stopwatch.StartNew();
            try
            {
                //Image<Hsv,int> 
                if (bitmap == null || bitmap.PixelFormat == PixelFormat.DontCare)
                    return null;

                var rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
                Bitmap temp = new Bitmap(rect.Width, rect.Height, bitmap.PixelFormat);
                var palette = bitmap.Palette;
                if (palette.Entries.Length > 0)
                    temp.Palette = palette;
                var tempData = temp.LockBits(rect, ImageLockMode.ReadWrite, bitmap.PixelFormat);
                var bmpData = bitmap.LockBits(rect, ImageLockMode.ReadOnly, bitmap.PixelFormat);
                int length = bmpData.Stride * bmpData.Height;
                int tLength = tempData.Stride * tempData.Height;
                byte[] pixs = new byte[length];
                Marshal.Copy(bmpData.Scan0, pixs, 0, length);
                bitmap.UnlockBits(bmpData);
                Marshal.Copy(pixs, 0, tempData.Scan0, tLength);
                temp.UnlockBits(tempData);
                return temp;
            }
            catch (Exception ex)
            {
                return null;
            }
            finally
            {
            }

        }

        private Bitmap DeepCopyBitmap2(Bitmap bitmap)
        {
            try
            {
                Bitmap bmp2 = new Bitmap(bitmap.Width, bitmap.Height, bitmap.PixelFormat);
                //将第一个bmp拷贝到bmp2中
                Graphics draw = Graphics.FromImage(bmp2);
                draw.DrawImage(bitmap, 0, 0);
                draw.Dispose();
                bitmap.Dispose();//释放bmp文件资源
                return bmp2;
            }
            catch (Exception ex)
            {
                return null;
            }
            finally
            {
            } 
        }
        
    
      [System.Runtime.InteropServices.DllImport("gdi32.dll")]
        public static extern bool DeleteObject(IntPtr hObject);

        private Bitmap DeepCopyBitmap3(Bitmap bitmap)
        {
            IntPtr jb = bitmap.GetHbitmap();
            Bitmap bittemp = Bitmap.FromHbitmap(jb);
            DeleteObject(jb);
            bitmap.Dispose();
            return bittemp;
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值