2011-05-03 3 views
9

BitmapSource의 일부를 WritableBitmap에 복사하려고합니다. 이것은 지금까지 내 코드입니다BitmapSource에서 WritableBitmap으로 복사

: "값 예상 범위를 벗어 ArgumentException이가."

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

내가 얻을 CopyPixels의 줄에

row.PixelHeight * row.BackBufferStriderow.PixelHeight * row.PixelWidth으로 바꾸려고 시도했지만 값이 너무 낮다는 오류가 표시됩니다.

CopyPixels의 과부하를 사용하여 단일 코드 예제를 찾을 수 없으므로 도움을 요청하고 있습니다.

감사합니다.

답변

19

복사하려는 이미지의 부분은 무엇입니까? 대상 ctor의 너비와 높이, Int32Rect의 너비와 높이뿐만 아니라 x & y 오프셋을 이미지의 처음 두 매개 변수 (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; 
+0

감사! 저는 BitmapSource에서 WritableBitmap으로 직접 복사 할 수 있기를 바랬습니다 ... 이제 CopyPixels의 이러한 과부하가 실제로해야 할 일이 무엇인지 궁금합니다. –

+1

사각형 오버로드로 비트 맵 이미지가 Int32Rect로 복사되므로 너무 유용하지 않습니다. WriteableBitmap에 전달하십시오. 정말 짧은 것을 원하고 전체 이미지를 복사하려면 : * WriteableBitmap target = 새 WriteableBitmap (Pic1.Source as BitmapSource); Pic2.Source = target; * –

+0

그리고 BitmapSource의 일부만 원한다면 (비교적 작은 높이와 같은 너비의 사각형이 필요합니다)? –