9

我正在尝试将 BitmapSource 的一部分复制到 WritableBitmap。

到目前为止,这是我的代码:

var bmp = image.Source as BitmapSource;
var row = new WriteableBitmap(bmp.PixelWidth, bottom - top, bmp.DpiX, bmp.DpiY, bmp.Format, bmp.Palette);
row.Lock();
bmp.CopyPixels(new Int32Rect(top, 0, bmp.PixelWidth, bottom - top), row.BackBuffer, row.PixelHeight * row.BackBufferStride, row.BackBufferStride);
row.AddDirtyRect(new Int32Rect(0, 0, row.PixelWidth, row.PixelHeight));
row.Unlock();

我得到“ArgumentException:值不在预期范围内”。在行中CopyPixels

我尝试row.PixelHeight * row.BackBufferStride与交换row.PixelHeight * row.PixelWidth,但随后我收到一个错误,提示该值太低。

我找不到使用这个重载的单个代码示例CopyPixels,所以我正在寻求帮助。

谢谢!

4

1 回答 1

20

图像的哪一部分试图复制?更改目标 ctor 中的宽度和高度,以及 Int32Rect 中的宽度和高度以及前两个参数 (0,0),它们是图像中的 x 和 y 偏移量。或者,如果您想复制整个内容,请离开。

BitmapSource source = sourceImage.Source as BitmapSource;

// Calculate stride of source
int stride = source.PixelWidth * (source.Format.BitsPerPixel + 7) / 8;

// Create data array to hold source pixel data
byte[] data = new byte[stride * source.PixelHeight];

// Copy source image pixels to the data array
source.CopyPixels(data, stride, 0);

// Create WriteableBitmap to copy the pixel data to.      
WriteableBitmap target = new WriteableBitmap(
  source.PixelWidth, 
  source.PixelHeight, 
  source.DpiX, source.DpiY, 
  source.Format, null);

// Write the pixel data to the WriteableBitmap.
target.WritePixels(
  new Int32Rect(0, 0, source.PixelWidth, source.PixelHeight), 
  data, stride, 0);

// Set the WriteableBitmap as the source for the <Image> element 
// in XAML so you can see the result of the copy
targetImage.Source = target;
于 2011-05-03T10:54:59.377 回答