Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy a rectangluar portion of Bitmap using LockBits

Tags:

c#

.net

winforms

I'm using the following code to lock a rectangle region of a bitmap

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

What seems to be the issue is bitmapData.Scan0 gives me IntPtr of the top left corner of the rectangle. When I use memcpy, it copies the contiguous region in memory upto the specified length.

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

If following is my bitmap data,

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

and if the rectangle is (2, 1, 3 ,3) i.e, the region

g h i
l m n
q r s

using memcpy gives me bitmap with the following region

g h i
j k l
m n o

I can understand why it copies the contiguous memory region. Bottom line is I want to copy a rectangle region using 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 than 500ms)

bitmap.RotateFlip(RotateFlipType.RotateNoneFlipY);

but it was very slow when I didn't flip Y (30 seconds)

Image size used was 60000x1500.

like image 846
Dinesh Avatar asked Nov 10 '22 15:11

Dinesh


1 Answers

Don't really get what your problem is. The following code copies the correct bitmap region into a managed array (I used 32bpp, alpha is always 255 for a 24bpp bitmap of course):

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);
like image 133
Robert S. Avatar answered Nov 15 '22 09:11

Robert S.