我想从我的WPF窗口创建缩略图,并想将它保存到数据库中,并在以后显示它。 请问有什么好的解决办法吗?
我已经开始与RenderTargetBitmap,但我无法找到任何简单的方法把它转换成字节。
RenderTargetBitmap bmp = new RenderTargetBitmap(180, 180, 96, 96, PixelFormats.Pbgra32);
bmp.Render(myWpfWindow);
使用user32.dll中和Graphics.CopyFromScreen()是不适合我,因为它是在这里 ,因为我想从用户做了截屏控制,以及。
谢谢
史蒂芬·罗宾斯写了一个伟大的博客帖子大约捕获控制,包含以下扩展方法的截图:
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甚至文件。 检查MSDN文档BitmapEncoder.Frames
,它具有保存到一个FileStream的例子。 你可以将其保存到任何流。
为了得到BitmapFrame
从RenderTargetBitmap
,只需使用创建BitmapFrame.Create(BitmapSource)
方法。
文章来源: How can I create thumbnail from WPF window and convert it into bytes[] so I can persist it?