zetar
zetar

Reputation: 1233

How can you copy part of a writeablebitmap to another writeablebitmap?

How would you copy a part from one WriteableBitmap to another WriteableBitmap? I've written and used dozens of 'copypixel' and transparent copies in the past, but I can't seem to find the equivalent for WPF C#.

This is either the most difficult question in the world or the easiest because absolutely nobody is touching it with a ten foot pole.

Upvotes: 1

Views: 3232

Answers (4)

Andreas
Andreas

Reputation: 4013

 public static void CopyPixelsTo(this BitmapSource sourceImage, Int32Rect sourceRoi, WriteableBitmap destinationImage, Int32Rect destinationRoi)
    {
        var croppedBitmap = new CroppedBitmap(sourceImage, sourceRoi);
        int stride = croppedBitmap.PixelWidth * (croppedBitmap.Format.BitsPerPixel / 8);
        var data = new byte[stride * croppedBitmap.PixelHeight];
        // Is it possible to Copy directly from the sourceImage into the destinationImage?
        croppedBitmap.CopyPixels(data, stride, 0);
        destinationImage.WritePixels(destinationRoi,data,stride,0);
    }

Upvotes: 1

Alex Fiannaca
Alex Fiannaca

Reputation: 31

I agree with Guy above that the easiest method is to simply use the WriteableBitmapEx library; however, the Blit function is for compositing a foreground and background image. The most efficient method to copy a part of one WriteableBitmap to another WriteableBitmap would be to use the Crop function:

var DstImg = SrcImg.Crop(new Rect(...));

Note that your SrcImg WriteableBitmap must be in the Pbgra32 format to be operated on by the WriteableBitmapEx library. If your bitmap isn't in this form, then you can easily convert it before cropping:

var tmp = BitmapFactory.ConvertToPbgra32Format(SrcImg);
var DstImg = tmp.Crop(new Rect(...));

Upvotes: 1

Guy
Guy

Reputation: 1512

Use WriteableBitmapEx from http://writeablebitmapex.codeplex.com/ Then use the Blit method as below.

    private WriteableBitmap bSave;
    private WriteableBitmap bBase;

    private void test()
    {
        bSave = BitmapFactory.New(200, 200); //your destination
        bBase = BitmapFactory.New(200, 200); //your source
        //here paint something on either bitmap.
        Rect rec = new Rect(0, 0, 199, 199);
        using (bSave.GetBitmapContext())
        {
            using (bBase.GetBitmapContext())
            {
                bSave.Blit(rec, bBase, rec, WriteableBitmapExtensions.BlendMode.Additive);
            }
        }
    }

you can use BlendMode.None for higher performance if you don't need to preserve any information in your destination. When using Additive you get alpha compositing between source and destination.

Upvotes: 3

There does not appear to be a way to copy directly from one to another but you can do it in two steps using an array and CopyPixels to get them out of one and then WritePixels to get them into another.

Upvotes: 2

Related Questions