首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从BitmapSource复制到WritableBitmap

从BitmapSource复制到WritableBitmap
EN

Stack Overflow用户
提问于 2011-05-03 17:37:03
回答 1查看 15.4K关注 0票数 9

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

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

代码语言:javascript
复制
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.PixelWidth交换row.PixelHeight * row.BackBufferStride,但是我得到一个错误,说这个值太低。

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

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-05-03 18:54:59

图像的哪一部分正在尝试复制?更改目标ctor中的宽度和高度、Int32Rect中的宽度和高度以及图像中的前两个参数(0,0),它们是x&y偏移量。或者,如果你想复制整个东西,就直接离开。

代码语言:javascript
复制
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;
票数 20
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5867657

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档