如何复制WriteableBitmap的一部分?

3

我有一些WriteableBitmap对象。假设实际上在WriteableBitmap对象上的图像大小为600x400。

我想复制图像的一部分 - 例如WriteableBitmap中间的100x100矩形,并将副本粘贴到其他图像控件中。

我该如何做?

2个回答

4

我猜您现在已经解决了这个问题,但我遇到了相同的问题并找到了答案,所以我想发布一下。 在http://writeablebitmapex.codeplex.com/网站上的代码有一个“Crop”例程,可以完成您需要的几乎所有操作。一旦您设置了一个值为4的SizeOfArgb常量,就可以使用以下代码:

public static WriteableBitmap Crop(this WriteableBitmap bmp, int x, int y, int width, int height)
      {
         var srcWidth = bmp.PixelWidth;
         var srcHeight = bmp.PixelHeight;

         // If the rectangle is completly out of the bitmap
         if (x > srcWidth || y > srcHeight)
         {
            return new WriteableBitmap(0, 0);
         }

         // Clamp to boundaries
         if (x < 0) x = 0;
         if (x + width > srcWidth) width = srcWidth - x;
         if (y < 0) y = 0;
         if (y + height > srcHeight) height = srcHeight - y;

         // Copy the pixels line by line using fast BlockCopy
         var result = new WriteableBitmap(width, height);
         for (var line = 0; line < height; line++)
         {
            var srcOff = ((y + line) * srcWidth + x) * SizeOfArgb;
            var dstOff = line * width * SizeOfArgb;
            Buffer.BlockCopy(bmp.Pixels, srcOff, result.Pixels, dstOff, width * SizeOfArgb);
         }
         return result;
      }

我认为上面的代码不起作用。我无法让它工作,因为它只返回未裁剪的原始bmp图像。 - hewstone
SizeOfArgb是什么? - jayarjo
1
就像我之前提到的那样,它是4。 - Chris Rae

1
    public static BitmapSource Crop(this BitmapSource bmp, Int32Rect rect)
    {
        return new CroppedBitmap(bmp, rect);
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接