从的BitmapSource复制到WritableBitmap [英] Copying from BitmapSource to WritableBitmap

查看:999
本文介绍了从的BitmapSource复制到WritableBitmap的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图复制的BitmapSource到WritableBitmap的一部分

I am trying to copy a part of a BitmapSource to a WritableBitmap.

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

This is my code so far:

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.BackBufferStride row.PixelHeight * row.PixelWidth ,但后来我得到一个错误说价值太低了。

I tried swapping row.PixelHeight * row.BackBufferStride with row.PixelHeight * row.PixelWidth, but then I get an error saying the value is too low.

我不能使用 CopyPixels 的这种超负荷找到一个单一的代码示例,所以我寻求帮助。

I couldn't find a single code example using this overload of CopyPixels, so I'm asking for help.

谢谢!

推荐答案

哪一部分的形象正试图复制?改变在目标构造函数的宽度和高度,并在Int32Rect的宽度和高度以及所述第一两个参数(0,0),其分别为x&放大器; y偏移到图像。 。或者只是离开,如果要复制整个事情

What part of the image are trying to copy? change the width and height in the target ctor, and the width and height in Int32Rect as well as the first two params (0,0) which are x & y offsets into the image. Or just leave if you want to copy the whole thing.

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;

这篇关于从的BitmapSource复制到WritableBitmap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆