此方法使用不安全代码,假设位图大小相同且每像素 4 个字节。
Rectangle bounds = new Rectangle(0,0,bitmapA.Width,bitmapA.Height);
var bmpDataA = bitmapA.LockBits(bounds, ImageLockMode.ReadWrite, bitmapA.PixelFormat);
var bmpDataB = bitmapB.LockBits(bounds, ImageLockMode.ReadWrite, bitmapB.PixelFormat);
const int height = 720;
int npixels = height * bmpDataA.Stride/4;
unsafe {
int * pPixelsA = (int*)bmpDataA.Scan0.ToPointer();
int * pPixelsB = (int*)bmpDataB.Scan0.ToPointer();
for ( int i = 0; i < npixels; ++i ) {
if (pPixelsA[i] != pPixelsB[i]) {
pPixelsB[i] = Color.Black.ToArgb();
}
}
}
bitmapA.UnlockBits(bmpDataA);
bitmapB.UnlockBits(bmpDataB);
对于安全的方法,将像素数据复制到数组缓冲区以使用这些InteropServices.Marshal.Copy
方法进行处理。