I’m spending the bulk of my time these days writing applications for Windows phones using Silverlight for Windows Phone (and having a blast doing it, I might add). As I write, I think of lots of little tips that can save time, reduce aggravation, and help all of us build better applications. So I thought I’d begin a series of tips that I can add to over time. This is the first in that series.

The Silverlight for Windows Phone documentation contains a helpful article demonstrating how to encode a WriteableBitmap as a JPEG and use the XNA framework’s MediaLibrary class to save it in the phone’s pictures library. The code works, but it’s way more work than you have to do.

Rather than create a temporary file in isolated storage, write the JPEG into the temporary file, transfer the JPEG from isolated storage into the pictures library, and then delete the file per the example in the documentation, you can accomplish the same thing with four lines of code:

 

using (MemoryStream stream = new MemoryStream(bitmap.PixelWidth * bitmap.PixelHeight * 4))

{

    Extensions.SaveJpeg(bitmap, stream, bitmap.PixelWidth, bitmap.PixelHeight, 0, 100);

    MediaLibrary library = new MediaLibrary();

    library.SavePicture(“SavedPicture.jpg”, stream.ToArray());

}

 

In this example, bitmap is a variable containing a reference to the WriteableBitmap you wish to encode and save. The MediaLibrary class is found in the Microsoft.Xna.Framework assembly, so you’ll need to add a reference to that assembly to your project in order to use it.