Question

Je suis en train de copier une partie d'un BitmapSource à un WritableBitmap.

Ceci est mon code à ce jour:

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();

get « ArgumentException: La valeur ne tombe pas dans la plage attendue. » dans la ligne de CopyPixels.

J'ai essayé avec échange row.PixelHeight * row.BackBufferStride row.PixelHeight * row.PixelWidth, mais je reçois une erreur disant que la valeur est trop faible.

Je ne pouvais pas trouver un seul exemple de code utilisant cette surcharge de CopyPixels, donc je demander de l'aide.

Merci!

Était-ce utile?

La solution

Quelle partie de l'image tentent de copier? modifier la largeur et la hauteur dans le cteur cible, et la largeur et la hauteur dans Int32Rect ainsi que les deux premières params (0,0) qui sont x et des décalages y dans l'image. Ou tout simplement laisser si vous voulez copier la chose.

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;
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top