使用 LockBits 复制位图的矩形部分

Din*_*esh 5 .net c# winforms

我正在使用以下代码锁定位图的矩形区域

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

问题似乎是bitmapData.Scan0给了我IntPtr矩形的左上角。当我使用 时memcpy,它将内存中的连续区域复制到指定的长度。

memcpy(bitmapdest.Scan0, bitmapData.Scan0, 
             new UIntPtr((uint (rect.Width*rect.Height*3)));
Run Code Online (Sandbox Code Playgroud)

如果以下是我的位图数据,

a b c d e
f g h i j
k l m n o
p q r s t
Run Code Online (Sandbox Code Playgroud)

如果矩形是(2, 1, 3 ,3)即区域

g h i
l m n
q r s
Run Code Online (Sandbox Code Playgroud)

使用memcpy为我提供了以下区域的位图

g h i
j k l
m n o
Run Code Online (Sandbox Code Playgroud)

我可以理解为什么它会复制连续的内存区域。底线是我想使用Lockbits.

编辑:我用过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);
}
Run Code Online (Sandbox Code Playgroud)

但是当我翻转时它更快Y(小于500ms)

bitmap.RotateFlip(RotateFlipType.RotateNoneFlipY);
Run Code Online (Sandbox Code Playgroud)

但是当我没有翻转时它很慢Y(30秒)

使用的图像大小为60000x1500.

Rob*_* S. 1

不太明白你的问题是什么。以下代码将正确的位图区域复制到托管数组中(我使用 32bpp,当然对于 24bpp 位图,alpha 始终为 255):

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);
Run Code Online (Sandbox Code Playgroud)