Mar*_*rek 1 c# wpf screenshot image
我想从我的wpf窗口创建缩略图,并希望将其保存到数据库中并稍后显示.有什么好的解决方案吗?
我已经开始使用RenderTargetBitmap,但我找不到任何简单的方法将它变成字节.
RenderTargetBitmap bmp = new RenderTargetBitmap(180, 180, 96, 96, PixelFormats.Pbgra32);
bmp.Render(myWpfWindow);
Run Code Online (Sandbox Code Playgroud)
使用user32.dll和Graphics.CopyFromScreen()对我来说并不好,因为它在这里是因为我想从用户控件做一个截图.
谢谢
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;
}
}
Run Code Online (Sandbox Code Playgroud)
此方法采用控件和比例因子并返回字节数组.所以这似乎非常适合您的要求.
查看帖子以获得进一步阅读和一个非常整洁的示例项目.
| 归档时间: |
|
| 查看次数: |
2791 次 |
| 最近记录: |