【问题标题】:How to copy an Image into a section of a WriteableBitmap (C# & WPF)如何将图像复制到 WriteableBitmap 的一部分(C# 和 WPF)
【发布时间】:2017-03-02 01:30:28
【问题描述】:

如果这是重复的,非常抱歉。 我正在像这样 (sn-p) 的画布的特定部分上写一些 BitmapImages。它工作正常:

  TreeFile = "pack://application:,,,/Images/" + TreeFile;

                        var image = new Image
                        {
                            Source = new BitmapImage(new Uri(TreeFile))
                        };
                        image.Width = 10;
                        image.Height = 10;

                        Canvas.SetLeft(image, x );
                        Canvas.SetTop(image, y );
                        MainCanvas.Children.Add(image);

我想做的是将image同时复制到WriteableBitmap BlankMap;在同一位置(MainCanvas 和 BlankMap 大小相同)。这是为了创建一个“撤消”。然后,假设用户想要将新的合成图像副本BlankMap保留到最终的BitmapImage WorkingMap;最后,我需要将现在完成的WorkingMap保存到磁盘。

所以我的问题是:

  1. 使用 WriteableBitmaps 是否正确?
  2. 我该如何写imageBlankMap
  3. 我该如何写BlankMapWorkingMap(尽管#2 和#3 可能是同一个问题/答案。

谢谢!如果这是某种形式的重复问题,再次道歉。

【问题讨论】:

  • 您阅读了多少 WriteableBitmap 类文档? msdn.microsoft.com/en-us/library/… 有一些陷阱,但在我冒险回答之前,我需要知道我应该有多深入。
  • 我对 WriteableBitmap 非常熟悉。我已经有一段时间没有在 WPF 工作了。

标签: c# wpf bitmapimage writeablebitmapex


【解决方案1】:

根据我使用映射工具的经验,我担心您所应用的思维过程在 WinForms 中有意义并在 WPF 中引起问题。请小心在 WPF 中生成的图像,因为它们很容易由于框架中长期存在的错误而泄漏内存。

问题 #1

这是执行“撤消”功能的正确方法吗?不会。但是,WPF 允许您非常轻松地添加、移动和删除元素。

我相信您的设想是,您将使用命令来实现更改,然后在您想要撤消命令时从堆栈中撤消命令。但是,我还没有看到任何有意义的例子。

问题 #2

当您使用现有的ImageSource 初始化WriteableBitmap 时,您只需将其传递到构造函数中即可:

var BlankMap = new WriteableBitmap(image);

之后,您将按照class documentation 中列出的代码示例进行操作。

问题 #3

你可以逆转这个过程。


最重要的是,听起来您想要进行某种图形编辑。位图在 WinForms 中工作得很好,因此很容易让人相信它们在 WPF 中也能工作得一样好。他们不。如果您将位图的使用限制为仅显示,那么您将更容易处理内存泄漏等问题。

【讨论】:

    【解决方案2】:

    这对我有用:

        public static void CopyImageTo(Image sourceImage, int x, int y, WriteableBitmap target)
        {
            BitmapSource source = sourceImage.Source as BitmapSource;
    
            int sourceBytesPerPixel = GetBytesPerPixel(source.Format);
            int sourceBytesPerLine = source.PixelWidth * sourceBytesPerPixel;
    
            byte[] sourcePixels = new byte[sourceBytesPerLine * source.PixelHeight];
            source.CopyPixels(sourcePixels, sourceBytesPerLine, 0);
    
            Int32Rect sourceRect = new Int32Rect(x, y, source.PixelWidth, source.PixelHeight);
            target.WritePixels(sourceRect, sourcePixels, sourceBytesPerLine, 0);
        }
    
        public static int GetBytesPerPixel(PixelFormat format)
        {
            return format.BitsPerPixel / 8;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-15
      • 2011-05-21
      • 2017-12-27
      • 2016-09-17
      • 2014-08-02
      • 2013-03-09
      • 2015-05-24
      • 1970-01-01
      相关资源
      最近更新 更多