Saturday, August 11, 2012

Saving Images with C#

I am making this very basic tutorial because it was hard for me to change from the old beta's way. It used to just be:

         colorImage.WritePixels(new Int32Rect(0, 0, colorImage.PixelWidth, colorImage.PixelHeight),  
           pixels, colorImage.PixelWidth * 4, 0);  
   
        colorImage.Save(path, ImageFormat.Jpeg);  

But now we have to use this long line of intense code to save one image, involving converting it to a RenderBitmap, then save it using an Encoder. Here is the new and complicated way of doing it.
               BitmapEncoder encoder = new JpegBitmapEncoder();  
   
               encoder.Frames.Add(BitmapFrame.Create(colorImage));  
   
               try  
               {  
                 using (FileStream fs = new FileStream(path, FileMode.Create))  
                 {  
                   encoder.Save(fs);  
                 }  
               }  
   
               catch (IOException)  
               {  
                 MessageBox.Show("Save Failed");  
               }  
Alright, I exaggerated, it is not that complicated, but it is a lot less understandable. But I am fine with it since it is more efficient and you can use this method to save anything, like a canvas which I will cover in my next post. See you then!

1 comment:

  1. great this is very helpful and demonstrate a lot for me :) but i wanna to ask where to implement this cod is in AllFramesReady event handler or in the button or where ?
    thanks :)

    ReplyDelete