在不损失质量的情况下截取具有预定义图像大小的 WPF window 的屏幕截图

Take a screenshot of a WPF window with the predefined image size without losing quality

当我截取当前 WPF window 的屏幕截图时,图像分辨率是我的显示器的分辨率(如果应用已最大化),这没问题。但是,如果我将该图像打印成更大的格式,图像看起来会很模糊。我找到了捕获当前 window 并将其保存为 png 文件的方法,但它并没有起到作用。图像以我设置的分辨率保存,但实际 wpf window 只占用保存图像的一小部分。示例取自:

http://blogs.msdn.com/b/saveenr/archive/2008/09/18/wpf-xaml-saving-a-window-or-canvas-as-a-png-bitmap.aspx

        var screen = System.Windows.Application.Current.Windows.OfType<Window>().SingleOrDefault(x => x.IsActive);

        var rtb = new RenderTargetBitmap(4000, 4000, 96, 96, PixelFormats.Pbgra32);

        rtb.Render(screen);

        var enc = new System.Windows.Media.Imaging.PngBitmapEncoder();
        enc.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(rtb));

        using (var stm = System.IO.File.Create("ScreenShot.png"))
        {
            enc.Save(stm);
            using (Image img = Image.FromStream(stm))
            {
                Rectangle dest = new Rectangle(0, 0, 6000, 4000);

                using (Graphics imgG = Graphics.FromImage(img))
                {
                    imgG.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    imgG.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    imgG.DrawImage(img, dest);
                }

                img.Save("NewScreenShot.png");
            }
        }

所以基本上,如果可能的话,我想以 4000 x 4000 的分辨率截取屏幕截图,而不会降低质量。 上面的代码生成了一张 4000 x 4000 的图像,但是屏幕截图只截取了它的一小部分,即原始分辨率。

要缩放图像,您可以使用 DrawingVisualScaleTransform :

var w = 4000;
var h = 4000;

var screen = System.Windows.Application.Current.Windows.OfType<Window>().SingleOrDefault(x => x.IsActive);

var visual = new DrawingVisual();
using (var context = visual.RenderOpen())
{
    context.DrawRectangle(new VisualBrush(screen),
                          null,
                          new Rect(new Point(), new Size(screen.Width, screen.Height)));
}

 visual.Transform = new ScaleTransform(w / screen.ActualWidth, h / screen.ActualHeight);

 var rtb = new RenderTargetBitmap(w, h, 96, 96, PixelFormats.Pbgra32);
 rtb.Render(visual);

 var enc = new PngBitmapEncoder();
 enc.Frames.Add(BitmapFrame.Create(rtb));

 using (var stm = File.Create("ScreenShot.png"))
 {
     enc.Save(stm);
 }