按一个button实现截图
先看XAML:`
Window x:Class="BMPGenerator.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" >
<Grid>
<StackPanel HorizontalAlignment="Left" Height="319" VerticalAlignment="Top" Width="517" >
<Canvas x:Name="MainCanvas" Height="270" >
<Canvas.Background>
<ImageBrush ImageSource="C:\Users\pandong\Documents\Visual Studio 2012\Projects\BMPGenerator\BMPGenerator\Resources\aaa.jpg" Stretch="Fill" TileMode="FlipXY"/>
</Canvas.Background> //这里是导入背景图片
</Canvas>
<Button x:Name="Button" Content="PicGenerate" Click="Button_Click" >
<Button.Background>
<ImageBrush ImageSource="C:\Users\pandong\Documents\Visual Studio 2012\Projects\BMPGenerator\BMPGenerator\Resources\aaa.jpg" Stretch="Fill"/>
</Button.Background>
</Button>
</StackPanel>
</Grid>
</Window>
效果如下
主代码如下:
代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Windows.Forms;
namespace BMPGenerator
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
//保存图片处理事件
private void Button_Click(object sender, RoutedEventArgs e)
{
string outputfile = "";
System.Windows.Forms.SaveFileDialog saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
saveFileDialog1.Filter = "Png Files|*.png|Jpeg Image|*.jpg|Gif Image|*.gif"; //文件保存的格式
if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
outputfile = saveFileDialog1.FileName; //获取的名字里面包含路径
if (outputfile != "")
{
GetPicFromControl(MainCanvas, "BMP", @outputfile); //MainCanvas是要截图的控件
}
}
//FrameworkElement 为wpf元素提供wpf框架级的属性、事件和方法集
//截图
private void GetPicFromControl(FrameworkElement element, String type, String outputPath)
{
var bitmapRender = new RenderTargetBitmap((int)element.ActualWidth, (int)element.ActualHeight, 96, 96, PixelFormats.Pbgra32);//初始化一个系统windows媒体成像渲染目标位图类的新实例,它具有指定的参数
bitmapRender.Render(element);
BitmapEncoder encoder = null; //将XX对象的集合编码到图像流中
switch (type.ToUpper() )
{
case "BMP":
encoder = new BmpBitmapEncoder();
break;
case "GIF":
encoder = new GifBitmapEncoder();
break;
case "JPEG":
encoder = new JpegBitmapEncoder();
break;
case "PNG":
encoder = new PngBitmapEncoder();
break;
case "TIFF":
encoder = new TiffBitmapEncoder();
break;
default:
break;
}
encoder.Frames.Add(BitmapFrame.Create(bitmapRender)); //根据提供的参数创建一个新的位图
using (var file = File.Create(outputPath)) //在指定的路径outputPath中创建或覆盖文件
encoder.Save(file);
}
}
}