我如何从WPF窗口创建缩略图并将其转换为字节[],以便我可以持久化它

本文关键字:字节 持久化 我可以 转换 WPF 窗口 创建 略图 | 更新日期: 2023-09-27 18:11:14

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

我已经开始使用RenderTargetBitmap,但我找不到任何简单的方法来把它变成字节。

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

使用user32.dll和Graphics.CopyFromScreen()不适合我和因为我也想从用户控件做一个截图

谢谢

我如何从WPF窗口创建缩略图并将其转换为字节[],以便我可以持久化它

Steven Robbins写了一篇关于捕获控件截图的博文,其中包含以下扩展方法:

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;
    }
}

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

查看这篇文章的进一步阅读和一个非常整洁的示例项目。

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

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