代码之家  ›  专栏  ›  技术社区  ›  Richard Slater

将两个位图与System.Windows.Media.Imaging组合在一起

  •  2
  • Richard Slater  · 技术社区  · 15 年前

    我正在尝试使用System.Windows.Media.Imaging将两个大小和格式相同的位图合成为第三个大小和格式相同的文件。我是在WPF(在LINQPad中处理代码)的上下文之外执行此操作的,因为这样做的目的是将其作为不受支持的System.Drawing的替代品应用到ASP.net应用程序中。

    // load the files
    var layerOne = new BitmapImage(new Uri(layerOneFile, UriKind.Absolute));
    var layerTwo = new BitmapImage(new Uri(layerTwoFile, UriKind.Absolute));
    
    // create the destination based upon layer one
    var composite = new WriteableBitmap(layerOne);
    
    // copy the pixels from layer two on to the destination
    int[] pixels = new int[(int)layerTwo.Width * (int)layerTwo.Height];
    int stride = (int)(4 * layerTwo.Width);
    layerTwo.CopyPixels(pixels, stride, 0);
    composite.WritePixels(Int32Rect.Empty, pixels, stride, 0);
    
    // encode the bitmap to the output file
    PngBitmapEncoder encoder = new PngBitmapEncoder();
    encoder.Frames.Add(BitmapFrame.Create(composite));
    using (var stream = new FileStream(outputFile, FileMode.Create))
    {
        encoder.Save(stream);
    }
    

    这将创建一个与从layerOne加载的文件相同的文件,我希望layerTwo被覆盖在layerOne上。似乎发生的是数据被写入BackBuffer,但从未被渲染到位图上。。。大概这是调度员通常会做的事情。

    我哪里做错了?我怎么才能回到正轨?

    1 回复  |  直到 15 年前
        1
  •  3
  •   Jeff Ogata    15 年前

    问题在于 WritePixels ,表示 WriteableBitmap 更新。

    而不是 Int32Rect.Empty ,您可以执行以下操作,并应看到在第一个图像上写入的第二个图像:

    Int32Rect sourceRect = new Int32Rect(0, 0, (int)layerTwo.Width, (int)layerTwo.Height);
    composite.WritePixels(sourceRect, pixels, stride, 0);