Click here to Skip to main content
15,945,344 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I'm using the following code.
BitmapData bitmapData = bitmap.LockBits(new rect(X,Y,width,height),
               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 copy using 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 <br />
f g h i j<br />
k l m n o<br />
p q r s t <br />

and if the rectangle portion is required (2, 1, 3 ,3) i.e, the region
<br />
g h i<br />
l m n<br />
q r s<br />

using memcpy gives me bitmap with the following region
<br />
g h i<br />
j k l<br />
m n o<br />

How can I still use Lockbits and achieve rectangluar region copy?
Updated 29-Oct-22 9:14am

1 solution

You don't have to use powerful LockBits for this simple purpose. Use one of System.Drawing.Graphics.DrawImage methods:[^].

Use only the method which don't specify the target size, the size of the copy; it will guarantee that you are copying the image as is, without re-sampling it.

Just in case: please don't tell me that this is not what you want because you are not going to render this image. It is what you want, because you can draw the image copy on any media: screen, printer, another image. To get the instance of the Graphics to draw on the bitmap using this factory function:[^].

Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900