private void SaveToImage(FrameworkElement surface, string fileName) { var transform = surface.LayoutTransform; surface.LayoutTransform = null; var size = new Size(surface.Width, surface.Height); surface.Measure(size); surface.Arrange(new Rect(size)); var renderBitmap = new RenderTargetBitmap( (int)size.Width, (int)size.Height, 96d, 96d, PixelFormats.Pbgra32); renderBitmap.Render(surface); using (var outStream = new FileStream(fileName, FileMode.Create)) { var encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(renderBitmap)); encoder.Save(outStream); } surface.LayoutTransform = transform; }surface为控件实例,fileName为保存的PNG图片的全路径名称。
下面的是另一段关于保存PNG的代码,但是和上面的没有什么直接的关系,只是为了自己记忆方便,所以这里放在一起。
private static void temp() { //428,243 var font10 = new Font("宋体", 10); var font16b = new Font("宋体", 16, FontStyle.Bold); Brush brush_b = new SolidBrush(Color.Black); var img = new Bitmap(1501, 1001); var g = Graphics.FromImage(img); g.FillRectangle(new SolidBrush(Color.White), 0, 0, 1500, 1000); const int gx0 = 428; const int gy0 = 243; var pen_b = new Pen(Color.Black); for (var x = 0; x < 31; x++) { g.DrawLine(pen_b, x * 50, 0, x * 50, 1000); } for (var y = 0; y < 21; y++) { g.DrawLine(pen_b, 0, y * 50, 1500, y * 50); } for (var x = 0; x < 31; x++) { for (var y = 0; y < 21; y++) { g.DrawString((gx0 + x).ToString(CultureInfo.InvariantCulture), font10, brush_b, x * 50 + 1, y * 50 + 1); g.DrawString((gy0 + y).ToString(CultureInfo.InvariantCulture), font10, brush_b, x * 50 + 1, y * 50 + 13); } } DataTable dt = conn.GetDataTable(" select gx,gy,count(*) as c from (select gx,gy,ci from ModelMR where gx>=428 and gx<=457 and gy>=243 and gy<=263 group by gx,gy,ci) a group by gx,gy order by c,gx,gy"); foreach (DataRow row in dt.Rows) { var c = int.Parse(row["c"].ToString()); if (c > 2) continue; var gx = int.Parse(row["gx"].ToString()) - gx0; var gy = int.Parse(row["gy"].ToString()) - gy0; g.DrawString(c.ToString(CultureInfo.InvariantCulture), font16b, brush_b, gx * 50 + 33, gy * 50 + 30); } img.Save(@"D:\1111.png", ImageFormat.Png); img.Dispose(); }
上面是WPF保存控件为图片的例子,下面是转载Silverlight把控件转为PNG图片的文章:
第一篇文字地址:http://dingtao-wgs.blog.163.com/blog/static/502607142010815105212137/
第二篇文字地址:http://www.cnblogs.com/ampedZ/archive/2012/12/29/GetBMP24Stream.html