2011-05-03 36 views
9

Tôi đang cố sao chép một phần của BitmapSource thành WritableBitmap.Sao chép từ BitmapSource sang WritableBitmap

Đây là mã của tôi cho đến nay:

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

tôi nhận được "ArgumentException: Giá trị không nằm trong phạm vi dự kiến." trong dòng CopyPixels.

Tôi đã thử đổi số row.PixelHeight * row.BackBufferStride bằng row.PixelHeight * row.PixelWidth, nhưng sau đó tôi gặp lỗi khi nói giá trị quá thấp.

Tôi không thể tìm thấy một ví dụ mã duy nhất sử dụng quá tải này CopyPixels, vì vậy tôi yêu cầu trợ giúp.

Cảm ơn!

Trả lời

19

Phần nào của hình ảnh đang cố sao chép? thay đổi chiều rộng và chiều cao trong ctor đích, và chiều rộng và chiều cao trong Int32Rect cũng như hai tham số đầu tiên (0,0) là x & y offset vào hình ảnh. Hoặc chỉ để lại nếu bạn muốn sao chép toàn bộ điều.

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

Cảm ơn! Tôi hy vọng rằng tôi có thể sao chép trực tiếp từ BitmapSource vào WritableBitmap ... Bây giờ tôi tự hỏi điều này quá tải của CopyPixels thực sự có nghĩa là làm gì ... –

+1

Quá tải hình chữ nhật sẽ sao chép hình ảnh bitmap thành Int32Rect do đó không hữu ích cho chuyển nó đến WriteableBitmap. Nếu bạn muốn một cái gì đó thực sự ngắn và bạn muốn sao chép toàn bộ hình ảnh: * WriteableBitmap target = new WriteableBitmap (Pic1.Source như BitmapSource); Pic2.Source = target; * –

+0

Và nếu tôi chỉ muốn một phần của BitmapSource (tôi cần một hình chữ nhật có chiều cao tương đối nhỏ và cùng chiều rộng)? –

Các vấn đề liên quan