using System.Windows.Media.Imaging;
using System.Windows.Media;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using Microsoft.Win32;
namespace WpfApplication1
{
class ImageOutput
{
public void GetImageFromControl(System.Windows.Controls.Control control)
{
///第一步:建立DrawingVisual,将Control转换为DrawingVisual
DrawingVisual drawingVisual = new DrawingVisual();
using (DrawingContext context = drawingVisual.RenderOpen())
{
VisualBrush brush = new VisualBrush(control) { Stretch = Stretch.None };
context.DrawRectangle(brush, null, new Rect(0, 0, control.Width, control.Height));
context.Close();
}
///第二步:建立RenderTargetBitmap,将DrawingVisual转化为RenderTargetBitmap
//dpi可以自己设定 // 获取dpi方法:PresentationSource.FromVisual(this).CompositionTarget.TransformToDevice
RenderTargetBitmap bitmap = new RenderTargetBitmap((int)control.Width, (int)control.Height, 96, 96, PixelFormats.Pbgra32);
bitmap.Render(drawingVisual);
///第三步:使用SaveFileDialog获得保存路径
///
bool flag = false;
folders = OpenRegistryPath(Registry.CurrentUser, @"/Software/Microsoft/Windows/CurrentVersion/Explorer/Shell Folders");
string picturesPath = folders.GetValue("Desktop").ToString();
string imagFile = "";
System.Windows.Forms.SaveFileDialog saveFileDialog = new System.Windows.Forms.SaveFileDialog();
saveFileDialog.Filter = "PNG文件(*.png)|*.png|JPG文件(*.jpg)|*.jpg|BMP文件(*.bmp)|*.bmp|GIF文件(*.gif)|*.gif|TIF文件(*.tif)|*.tif";
saveFileDialog.InitialDirectory = picturesPath;
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
flag = true;
imagFile = saveFileDialog.FileName;
}
///第四步:创建BitmapEncoder,保存图片
if (flag)
{
string extensionString = Path.GetExtension(imagFile);
BitmapEncoder encoder = null;
switch (extensionString)
{
case ".jpg":
encoder = new JpegBitmapEncoder();
break;
case ".png":
encoder = new PngBitmapEncoder();
break;
case ".bmp":
encoder = new BmpBitmapEncoder();
break;
case ".gif":
encoder = new GifBitmapEncoder();
break;
case ".tif":
encoder = new TiffBitmapEncoder();
break;
default:
throw new InvalidOperationException();
}
encoder.Frames.Add(BitmapFrame.Create(bitmap));
using (Stream stm = File.Create(imagFile))
{
encoder.Save(stm);
}
}
}
private RegistryKey folders;
private RegistryKey OpenRegistryPath(RegistryKey root, string s)
{
s = s.Remove(0, 1) + @"/";
while (s.IndexOf(@"/") != -1)
{
root = root.OpenSubKey(s.Substring(0, s.IndexOf(@"/")));
s = s.Remove(0, s.IndexOf(@"/") + 1);
}
return root;
}
}
}
以上代码的使用方法为:
ImageOutput imageOutput = new ImageOutput();
imageOutput.GetImageFromControl(“界面上的用户控件,可以是自定义的UserControl,也可以是一般的控件(如TextBox,Label等),但不能是Grid和Canvas,可能是它们和Control不在同一个命名空间,且不能相互转化”);