【问题标题】:How can I create thumbnail from WPF window and convert it into bytes[] so I can persist it?如何从 WPF 窗口创建缩略图并将其转换为 bytes[] 以便我可以保留它?
【发布时间】:2011-10-13 13:16:49
【问题描述】:

我想从我的 wpf 窗口创建缩略图,并想将其保存到数据库中并稍后显示。有什么好的解决办法吗?

我已经开始使用 RenderTargetBitmap,但我找不到任何简单的方法将其转换为字节。

RenderTargetBitmap bmp = new RenderTargetBitmap(180, 180, 96, 96, PixelFormats.Pbgra32);
bmp.Render(myWpfWindow);

使用 user32.dll 和 Graphics.CopyFromScreen() 对我不利,而且 因为它是here,因为我也想从用户控件中截屏。

谢谢

【问题讨论】:

  • RenderTargetBitmap 很好。
  • @AngelWPF 是的,但我如何从这里获取字节?我在 RenderTargetBitmap 上没有任何流?

标签: c# wpf image screenshot


【解决方案1】:

Steven Robbins 曾写过a great blog post 关于捕获控件的屏幕截图,其中包含以下扩展方法:

public static class Screenshot
{
    /// <summary>
    /// Gets a JPG "screenshot" of the current UIElement
    /// </summary>
    /// <param name="source">UIElement to screenshot</param>
    /// <param name="scale">Scale to render the screenshot</param>
    /// <param name="quality">JPG Quality</param>
    /// <returns>Byte array of JPG data</returns>
    public static byte[] GetJpgImage(this UIElement source, double scale, int quality)
    {
        double actualHeight = source.RenderSize.Height;
        double actualWidth = source.RenderSize.Width;

        double renderHeight = actualHeight * scale;
        double renderWidth = actualWidth * scale;

        RenderTargetBitmap renderTarget = new RenderTargetBitmap((int) renderWidth, (int) renderHeight, 96, 96, PixelFormats.Pbgra32);
        VisualBrush sourceBrush = new VisualBrush(source);

        DrawingVisual drawingVisual = new DrawingVisual();
        DrawingContext drawingContext = drawingVisual.RenderOpen();

        using (drawingContext)
        {
            drawingContext.PushTransform(new ScaleTransform(scale, scale));
            drawingContext.DrawRectangle(sourceBrush, null, new Rect(new Point(0, 0), new Point(actualWidth, actualHeight)));
        }
        renderTarget.Render(drawingVisual);

        JpegBitmapEncoder jpgEncoder = new JpegBitmapEncoder();
        jpgEncoder.QualityLevel = quality;
        jpgEncoder.Frames.Add(BitmapFrame.Create(renderTarget));

        Byte[] _imageArray;

        using (MemoryStream outputStream = new MemoryStream())
        {
            jpgEncoder.Save(outputStream);
            _imageArray = outputStream.ToArray();
        }

        return _imageArray;
    }
}

此方法采用控件和比例因子并返回一个字节数组。所以这似乎非常符合您的要求。

查看the post 以进一步阅读和一个非常简洁的示例项目。

【讨论】:

    【解决方案2】:

    您可以使用BitmapEncoder 将您的位图编码为PNG、JPG 甚至BMP 文件。查看BitmapEncoder.Frames 上的 MSDN 文档,其中有一个保存到 FileStream 的示例。您可以将其保存到任何流中。

    要从RenderTargetBitmap 中获取BitmapFrame,只需使用BitmapFrame.Create(BitmapSource) 方法创建即可。

    【讨论】:

    • 感谢它对我有用。虽然使用 renderTargetBitmap.Render(myWpfWindow);不会将图像大小调整为 RenderTargetBitmap 大小,而是裁剪图像的左上角。知道如何调整它的大小吗?谢谢
    猜你喜欢
    • 1970-01-01
    • 2012-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-17
    • 1970-01-01
    • 2023-04-01
    相关资源
    最近更新 更多