Follow by Email

Saturday, August 11, 2012

Saving an Image from a Canvas C#

Hey all, like I promised in my last post I will show you how to save a canvas image. This is really cool and useful (I think) and pretty simple.
 public void ExportToPng(Uri path,Canvas surface)  
     {  
       if(path == null) return;  
         Size size = new Size(surface.Width,surface.Height);  
         surface.Measure(size);  
         surface.Arrange(new Rect(size ));  
         RenderTargetBitmap renderBitmap = new RenderTargetBitmap(  
           (int)size.Width, //width  
           (int)size.Height, //height  
           96d, //dpi x  
           96d, //dpi y  
           PixelFormats.Pbgra32 // pixelformat  
           );  
         renderBitmap.Render(surface);  
       using (FileStream outstream = new FileStream(path.LocalPath,FileMode.Create))  
       {  
         JpegBitmapEncoder encoder = new JpegBitmapEncoder();  
         encoder.Frames.Add(BitmapFrame.Create(renderBitmap));  
         encoder.Save(outstream);  
       }  
     }  
That's all there is to it! I think it is really useful and I would like to use it more often. Hope this helps anyone who wanted to know it!

No comments:

Post a Comment