c# - 从 BitmapSource 复制到 WriteableBitmap

标签 c# wpf bitmapsource writablebitmap

我正在尝试将 BitmapSource 的一部分复制到 WritableBitmap。

到目前为止,这是我的代码:

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

我收到“ArgumentException:值不在预期范围内。”在 CopyPixels 行中。

我尝试将 row.PixelHeight * row.BackBufferStriderow.PixelHeight * row.PixelWidth 交换,但随后我收到一条错误消息,指出该值太低。

我找不到使用 CopyPixels 重载的单个代码示例,所以我寻求帮助。

谢谢!

最佳答案

试图复制图像的哪一部分?更改 objective-c tor 中的宽度和高度,Int32Rect 中的宽度和高度以及前两个参数 (0,0),它们是图像中的 x 和 y 偏移量。或者如果你想复制整个东西就离开。

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;

关于c# - 从 BitmapSource 复制到 WriteableBitmap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5867657/

相关文章:

c# - 以编程方式将列添加到 WPF 中的 ListView ?

c# - 如何仅知道图像路径将图像保存到剪贴板

C# WPF BitmapSource 内存泄漏?

c# - 图标文件在 Win7 中无效,只有字体缩放到 125%

c# - 使用 RabbitMQ 重新发送存储在错误队列中的消息

c# - 比较和对比 C++ 与 C# 命名空间层次结构

c# - InteropBitmap 到 BitmapImage

c# - 使用 StringComparer 反序列化 JSON 字典

c# - 强制加载 WPF 视觉对象的适当方式

c# - WPF 组合框 : Set SelectedItem to item not in ItemsSource -> Binding oddity