Copy the rectangular portion of the bitmap using LockBits

I use the following code to lock the rectangle rectangle region

Recangle rect = new rect(X,Y,width,height);
BitmapData bitmapData = bitmap.LockBits(rect, ImageLockMode.ReadOnly,
                        bitmap.PixelFormat);

The problem seems to be bitmapData.Scan0giving me the IntPtrtop left corner of the rectangle. When I use memcpy, it copies the contiguous region in memory to the specified length.

memcpy(bitmapdest.Scan0, bitmapData.Scan0, 
             new UIntPtr((uint (rect.Width*rect.Height*3)));

If the following is my raster data,

a b c d e
f g h i j
k l m n o
p q r s t

and if rectangle (2, 1, 3 ,3)ie, area

g h i
l m n
q r s

using memcpygives a bitmap with the next area

g h i
j k l
m n o

I can understand why it is copying an adjacent memory region. I want to copy an area of ​​a rectangle with Lockbits.

Edit : I used Bitmap.Clone,

using (Bitmap bitmap= (Bitmap)Image.FromFile(@"Data\Edge.bmp"))
{
     bitmap.RotateFlip(RotateFlipType.RotateNoneFlipY);
     Rectangle cropRect = new Rectangle(new Point(i * croppedWidth, 0),new Size(croppedWidth, _original.Height));
     _croppedBitmap= bitmap.Clone(cropRect, bitmap.PixelFormat);
}

but it was faster when I flipped Y(less 500ms)

bitmap.RotateFlip(RotateFlipType.RotateNoneFlipY);

, Y (30 )

60000x1500.

+4
1

, . ( 32bpp, 255 24bpp, ):

int x = 1;
int y = 1;
int w = 2;
int h = 2;

Bitmap bmp = new Bitmap(@"path\to\bitmap.bmp");

Rectangle rect = new Rectangle(x, y, w, h);
System.Drawing.Imaging.BitmapData bmpData =
    bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly,
    System.Drawing.Imaging.PixelFormat.Format32bppArgb);

IntPtr ptr = bmpData.Scan0;

int bytes = 4 * w * h;
byte[] rgbValues = new byte[bytes];

System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);

bmp.UnlockBits(bmpData);
0

All Articles