Domanda

Sto cercando di copiare una parte di un bitmapsource in un WriteblebitMap.

Questo è il mio codice finora:

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

Ricevo "Argomento Exception: il valore non rientra nell'intervallo previsto". nella linea di CopyPixels.

Ho provato a scambiare row.PixelHeight * row.BackBufferStride insieme a row.PixelHeight * row.PixelWidth, ma poi ricevo un errore dicendo che il valore è troppo basso.

Non sono riuscito a trovare un esempio di codice singolo usando questo sovraccarico di CopyPixels, quindi sto chiedendo aiuto.

Grazie!

È stato utile?

Soluzione

Quale parte dell'immagine sta cercando di copiare? Cambia la larghezza e l'altezza nel cTOR target e la larghezza e l'altezza in int32Rect, nonché i primi due parametri (0,0) che sono offset X&Y nell'immagine. O lascia semplicemente se vuoi copiare tutto.

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;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top