Wpf UserControl 截图

今天要对一个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

posted @ 2012-12-18 20:03  生态圈_行者  阅读(833)  评论(0编辑  收藏  举报