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.BackBufferStriderow.PixelHeight * row.PixelWidthましたが、値が低すぎるというエラーが表示されます。

この のオーバーロードを使用したコード例が 1 つも見つからなかったCopyPixelsので、助けを求めています。

ありがとう!

4

1 に答える 1

20

画像のどの部分をコピーしようとしていますか? ターゲット ctor の幅と高さ、Int32Rect の幅と高さ、およびイメージへの x & y オフセットである最初の 2 つのパラメーター (0,0) を変更します。または、全体をコピーしたい場合はそのままにしてください。

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 に答える