2011-05-03 29 views
9

Estoy tratando de copiar una parte de un BitmapSource a un WritableBitmap.Copiando de BitmapSource a WritableBitmap

Este es mi código hasta ahora:

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

consigo "ArgumentException: Valor no está dentro del rango esperado." en la línea de CopyPixels.

He intentado intercambiar row.PixelHeight * row.BackBufferStride con row.PixelHeight * row.PixelWidth, pero me sale un error diciendo que el valor es demasiado bajo.

No pude encontrar un solo ejemplo de código usando esta sobrecarga de CopyPixels, entonces estoy pidiendo ayuda.

Gracias!

Respuesta

19

¿Qué parte de la imagen está intentando copiar? cambie el ancho y la altura en el ctor objetivo, y el ancho y alto en Int32Rect, así como los primeros dos params (0,0) que son x & y desplazamientos en la imagen. O simplemente vete si quieres copiar todo.

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; 
+0

¡Gracias! Esperaba poder copiar directamente de BitmapSource a WritableBitmap ... Ahora me pregunto qué significa realmente esta sobrecarga de CopyPixels ... –

+1

La sobrecarga de rectángulo copiará la imagen de mapa de bits a Int32Rect, por lo que no es tan útil para pasar eso a WriteableBitmap. Si quiere algo realmente corto y quiere copiar toda la imagen: * WriteableBitmap target = new WriteableBitmap (Pic1.Source como BitmapSource); Pic2.Source = target; * –

+0

Y si solo quiero una parte de BitmapSource (¿necesito un rectángulo con una altura relativamente pequeña y el mismo ancho)? –