/// <summary>
/// 复制指定矩形中的位图像素数据
/// </summary>
/// <param name="source"></param>
/// <param name="stride"></param>
/// <returns></returns>
public static byte[,] CopyGray8Pixels(BitmapSource source, out int stride)
{
if (source.Format != PixelFormats.Gray8)
source = new FormatConvertedBitmap(source, PixelFormats.Gray8, null, 0);
byte[,] pixels = new byte[source.PixelHeight, source.PixelWidth];
stride = source.PixelWidth * ((source.Format.BitsPerPixel + 7) / 8);
GCHandle pinnedPixels = GCHandle.Alloc(pixels, GCHandleType.Pinned);
// 复制指定矩形中的位图像素数据
source.CopyPixels(
new Int32Rect(0, 0, source.PixelWidth, source.PixelHeight),
pinnedPixels.AddrOfPinnedObject(),
pixels.GetLength(0) * pixels.GetLength(1) * 3, stride);
pinnedPixels.Free();
return pixels;
}