Wpf UserControl 截图

本文介绍了一种使用C#从UI元素获取JPEG截图的方法,通过将UI元素转换为byte[],然后将其转换为BitMapSource,实现对包含滚动条的UserControl进行截图。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天要对一个UserControl进行截图,因为该userControl 本身可能出现滚动条,因此采用一般的截屏的方式不可行,在网上找了找,结果发现了将该控件元素直接转换成byte[]的方法,然后再将byte[]换成相应的BitMapSource之类的图形元素。

具体如下所示:

public static byte[] GetJpgImage(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;
}

public static BitmapImage ImageFromBuffer(Byte[] bytes)
{
  MemoryStream stream = new MemoryStream(bytes);
  BitmapImage image = new BitmapImage();
  image.BeginInit();
  image.StreamSource = stream;
  image.EndInit();
  return image;
}

public Byte[] BufferFromImage(BitmapImage imageSource)
{
  Stream stream = imageSource.StreamSource;
  Byte[] buffer = null;
  if (stream != null && stream.Length > 0)
  {
    using (BinaryReader br = new BinaryReader(stream))
    {
      buffer = br.ReadBytes((Int32)stream.Length);
    }
  }

  return buffer;
}

 

引自:http://stackoverflow.com/questions/2977385/wpf-screenshot-jpg-from-uielement-with-c-sharp

转载于:https://www.cnblogs.com/challenger007/archive/2012/12/18/UserControlCreateScreenShot.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值