C# Bitmap 處理


        /// <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;
        }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章