Taking Screenshots in WPF
Its Very Easy. Look Below:
public static byte[] GetPNGImage(UIElement source, double scale, int quality)
{
double actualHeight = source.RenderSize.Height;
double actualWidth = source.RenderSize.Width;
double renderHeight = actualHeight*scale;
double renderWidth = actualWidth*scale;
var 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));
var myRect = new Rect(new System.Windows.Point(0, 0), new System.Windows.Point(actualWidth, actualHeight));
drawingContext.DrawRectangle(sourceBrush, null, myRect);
}
renderTarget.Render(drawingVisual);
JpegBitmapEncoder jpgEncoder = new JpegBitmapEncoder
{
QualityLevel = quality
};
jpgEncoder.Frames.Add(BitmapFrame.Create(renderTarget));
Byte[] imageArray;
using (var outputStream = new MemoryStream())
{
jpgEncoder.Save(outputStream);
imageArray = outputStream.ToArray();
}
return imageArray;
}
Dheeraj.
public static byte[] GetPNGImage(UIElement source, double scale, int quality)
{
double actualHeight = source.RenderSize.Height;
double actualWidth = source.RenderSize.Width;
double renderHeight = actualHeight*scale;
double renderWidth = actualWidth*scale;
var 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));
var myRect = new Rect(new System.Windows.Point(0, 0), new System.Windows.Point(actualWidth, actualHeight));
drawingContext.DrawRectangle(sourceBrush, null, myRect);
}
renderTarget.Render(drawingVisual);
JpegBitmapEncoder jpgEncoder = new JpegBitmapEncoder
{
QualityLevel = quality
};
jpgEncoder.Frames.Add(BitmapFrame.Create(renderTarget));
Byte[] imageArray;
using (var outputStream = new MemoryStream())
{
jpgEncoder.Save(outputStream);
imageArray = outputStream.ToArray();
}
return imageArray;
}
Dheeraj.
Comments
Post a Comment