0

I want to develop a function with the following signature:

 CopyImage(ImageSource inputImage, Point inTopLeft, Point InBottomRight, ImageSource outputImage, Point outTopLeft);

This function copy part of input image (ROI defined by inTopLeft and inBottomRight) and copy it to outputImage at outTopLeft.

I can do this in WPF by manipulating pixels, but I am looking for a solution that can do it much faster.

What is the fastest way to do this in WPF?

2
  • When you say "manipulating pixels", you mean BitmapSource.CopyPixels from the source and WriteableBitmap.WritePixels to the target? That would be pretty fast.
    – Clemens
    Nov 15, 2013 at 18:21
  • @Clemens No, I was thinking of getting each pixel and placing it to output. But this method seems very fast. Do you have any sample? If you, add it as an answer and I will accept it.
    – mans
    Nov 16, 2013 at 17:55

1 Answer 1

0

Your method could look like this:

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;
}
4
  • Better yet, use CroppedBitmap class. Nov 16, 2013 at 23:06
  • @Aybe And then get the pixel buffer from there to copy over the target? Doesn't make sense to me.
    – Clemens
    Nov 16, 2013 at 23:09
  • Using it you would save yourself doing a manual copy. On your code you never write to targetBitmap, did you forget something ? Nov 17, 2013 at 3:09
  • @Aybe You might have tested the code before commenting. Take a look at the WriteableBitmap constructor argument. It creates a copy of targetBitmap, before the copied rectange is written over it. And using CroppedBitmap would still require to get its pixel buffer by calling CopyPixels, so it's redundant.
    – Clemens
    Nov 17, 2013 at 9:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.