WPF裁剪图像的一部分

WPF Cropping a portion of an image

我创建了一个 WPF 应用程序,我需要允许用户在现有加载的图像(tif 图像)上绘制一个矩形,并将矩形的 coordinates/the 部分保存为单独的图像。

我正在使用 Leadtools.Windows.Controls 参考并使用 RasterImageViewer

下面是当用户完成绘制矩形时事件处理程序的代码。

private void ImageViewer_InteractiveUserRectangle(object sender, RectangleInteractiveEventArgs e)
    {
        if (e.Status == InteractiveModeStatus.End)
        {             

            var img = ImageViewer.Image;

            var top =Convert.ToInt32(e.Bounds.Top);
            var left = Convert.ToInt32(e.Bounds.Left);
            var width = Convert.ToInt32(e.Bounds.Width);
            var height = Convert.ToInt32(e.Bounds.Height);

            var rect = new Leadtools.LeadRect(left, top, width, height);
            var cmd = new Leadtools.ImageProcessing.CropCommand(rect);
            cmd.Run(img);

            _codecs.Save(img, @"c:\temp\test.tif",
                RasterImageFormat.CcittGroup4, 1, 1, 1, -1, CodecsSavePageMode.Append);
        }
    }

我得到了一个单独的裁剪图像,但它与用矩形绘制的区域不匹配。我尝试了示例中的各种方法,但它们都是针对 Windows Forms 应用程序而不是 WPF。对于我所缺少的任何帮助,将不胜感激。

问题是 ImageViewer UserRectangle 限制了 returns Control 坐标中的坐标,您需要将它们转换为裁剪命令正在寻找的图像坐标。

根据此处的文档: https://www.leadtools.com/help/leadtools/v19/dh/wl/rectangleinteractiveeventargs-bounds.html

The coordinates are always in control (display) to image coordinates. You can use PointToImageCoordinates and BoundsToImageCoordinates to map a value in control or display coordinates (what is on screen) to image coordinates (actual x and y location in the image pixels). You can use PointFromImageCoordinates and BoundsFromImageCoordinates to map a value in image coordinates (actual x and y location in t he image pixels) to control or display coordinates (what is on screen).

这里是更新后的代码,使其适用于您的项目:

if (e.Status == Leadtools.Windows.Controls.InteractiveModeStatus.End)
{
  var img = imageViewer.Image;

  var imgRect = imageViewer.BoundsToImageCoordinates(e.Bounds);

  var top = Convert.ToInt32(imgRect.Top);
  var left = Convert.ToInt32(imgRect.Left);
  var width = Convert.ToInt32(imgRect.Width);
  var height = Convert.ToInt32(imgRect.Height);

  var rect = new Leadtools.LeadRect(left, top, width, height);
  var cmd = new Leadtools.ImageProcessing.CropCommand(rect);
  cmd.Run(img);

  _codecs.Save(img, @"c:\temp\test.tif",
    RasterImageFormat.CcittGroup4, 1, 1, 1, -1, CodecsSavePageMode.Append);
}