Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在wpf中从一个图像复制ROI并复制到另一个图像上_C#_Wpf_Image Processing - Fatal编程技术网

C# 在wpf中从一个图像复制ROI并复制到另一个图像上

C# 在wpf中从一个图像复制ROI并复制到另一个图像上,c#,wpf,image-processing,C#,Wpf,Image Processing,我想开发一个具有以下签名的函数: CopyImage(ImageSource inputImage, Point inTopLeft, Point InBottomRight, ImageSource outputImage, Point outTopLeft); 此函数用于复制输入图像的一部分(由inTopLeft和inBottomRight定义的ROI),并将其复制到outTopLeft的outputImage 我可以通过操纵像素在WPF中实现这一点,但我正在寻找一种可以更快实现这一点的

我想开发一个具有以下签名的函数:

 CopyImage(ImageSource inputImage, Point inTopLeft, Point InBottomRight, ImageSource outputImage, Point outTopLeft);
此函数用于复制输入图像的一部分(由inTopLeft和inBottomRight定义的ROI),并将其复制到outTopLeft的outputImage

我可以通过操纵像素在WPF中实现这一点,但我正在寻找一种可以更快实现这一点的解决方案


在WPF中,最快的方法是什么

您的方法可能如下所示:

private BitmapSource CopyRegion(
    BitmapSource sourceBitmap, Int32Rect sourceRect,
    BitmapSource targetBitmap, int targetX, int targetY)
{
    if (sourceBitmap.Format != targetBitmap.Format)
    {
        throw new ArgumentException(
            "Source and target bitmap must have the same PixelFormat.");
    }

    var bytesPerPixel = (sourceBitmap.Format.BitsPerPixel + 7) / 8;
    var stride = bytesPerPixel * sourceRect.Width;
    var pixelBuffer = new byte[stride * sourceRect.Height];
    sourceBitmap.CopyPixels(sourceRect, pixelBuffer, stride, 0);

    var outputBitmap = new WriteableBitmap(targetBitmap);
    sourceRect.X = targetX;
    sourceRect.Y = targetY;
    outputBitmap.WritePixels(sourceRect, pixelBuffer, stride, 0);

    return outputBitmap;
}

当你说“操纵像素”时,你是指从源到目标?“那会很快的。”克莱门斯:不,我正在考虑获取每个像素并将其输出。但这种方法似乎很快。有样品吗?如果您愿意,请将其添加为答案,我将接受。更好的方法是使用CroppedBitmap类。@Aybe,然后从中获取像素缓冲区,以便在目标上复制?对我来说没有意义。使用它你可以省去手动复制。在你的代码中,你从来没有写过
targetBitmap
,你是否忘记了什么?也许你在评论之前已经测试过代码了。请看WriteableBitmap构造函数参数。在将复制的矩形范围写入targetBitmap之前,它会创建targetBitmap的副本。使用CroppedBitmap仍然需要通过调用CopyPixels来获取其像素缓冲区,因此这是多余的。