XNA from Silverlight on Windows Phone 7 – Saving Pictures

One of the things you might notice about the emulator – especially if you’re doing anything with imagery, is the lack of any pictures in your library. This can be a problem, particularly if you want to do any testing with thePhotoChooserTask but fear not, there is a way around it and yes, it uses XNA.

The idea is to check when your application starts whether it’s running in the emulator, and if it is, add some pictures so you have something to work with. You can do this using the Microsoft.Xna.Framework.Media.MediaLibrary class. This class has a SavePicture() method that allows you to save a JPEG image to the media library on the device.

Start be adding a reference to Microsoft.Xna.Framework to your project. I’ve added some images to a folder in the project called “Images” – their build action is set to “Content”. These are the images to be added to the “device” if we’re running on the emulator. Take a note of the filenames – we create a List<string> containing the filenames and enumerate that list to copy the images to the device.

 private void CheckAndAddPictures()
    // MediaLibrary IDisposable so using a using
    using (MediaLibrary myMediaLibrary = new MediaLibrary())
        // Check we're on the emulator and haven't already added images
        if ( Microsoft.Devices.Environment.DeviceType == DeviceType.Emulator &&
                myMediaLibrary.Pictures.Count == 0 )
            // Here's our list of image filenames
            List<string> photoList = new List<string>()

            // Enumerate the list 
            foreach (var item in photoList)
                // Create a URI with the folder name and filename
                Uri myUri = 
                    new Uri(string.Format(@"Images/{0}", item), UriKind.Relative);

                // Access the resource in the application package and save
                // the image to the media library
                using (Stream photoStream = App.GetResourceStream(myUri).Stream)
                    myMediaLibrary.SavePicture(item, photoStream);

As you can see it’s pretty straightforward. I call CheckAndAddPictures() from the constructor of the main page in my app. It checks to ensure I’m running in the emulator and the images haven’t already been added (as the emulator can persist across debug sessions) before creating a list of images to be added and adding them using the MediaLibrary class. Note that the MediaLibrary class implements IDisposable so I wrap it in a using statement.

That’s it. Implement the above, add a few images to your project and you’re good to go.