【问题标题】:Copying from BitmapSource to WritableBitmap从 BitmapSource 复制到 WriteableBitmap
【发布时间】:2011-05-03 09:37:03
【问题描述】:

我正在尝试将 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 重载的单个代码示例,所以我寻求帮助。

谢谢!

【问题讨论】:

    标签: c# wpf bitmapsource writablebitmap


    【解决方案1】:

    试图复制图像的哪一部分?更改目标 ctor 中的宽度和高度,以及 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;
    

    【讨论】:

    • 谢谢!我有点希望我可以直接从 BitmapSource 复制到 WritableBitmap... 现在我想知道 CopyPixels 的这种重载真正意味着什么...
    • 矩形重载会将位图图像复制到 Int32Rect,因此将其传递给 WriteableBitmap 并没有多大用处。如果您想要一些非常短的内容并且想要复制整个图像: WriteableBitmap target = new WriteableBitmap(Pic1.Source as BitmapSource); Pic2.Source = 目标;
    • 如果我只想要 BitmapSource 的一部分(我需要一个高度相对较小且宽度相同的矩形)?
    • 如果每个像素使用一个字节,这将中断。 “每像素字节数”的正确步幅计算为 (bitsPerPixel + 7) / 8
    • 答案中有width * (bitsPerPixel + 7) / 8。它不应该是width * ((bitsPerPixel + 7) / 8) 吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-15
    • 1970-01-01
    相关资源
    最近更新 更多