wolfgang ziegler


„make stuff and blog about it“

Saving an Image to the Media Library on Windows Phone

February 11, 2014

Quite often, Windows Phone apps let their users save images to the device’s media library. So, what does the source code for enabling this feature look like? It’s actually quite simple, and can be done in just few steps. Let’s assume we have a WriteableBitmap object we want to persist.

Creating an Isolated Storage File

First we have to create a file in the app’s isolated storage. The actual file name is not relevant here, so we just use a GUID.

var tempName = Guid.NewGuid().ToString();
var store = IsolatedStorageFile.GetUserStoreForApplication();
var fileStream = store.CreateFile(tempName);

Saving the Image to Isolated Storage.

Before saving to the actual media library folder, we need to place the the file into isolated storage and encode it as JPEG. Fortunately, there is a handy helper class for that

WriteableBitmap wb; // the image we want to save
Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 100);
fileStream.Close();

Storing the Image in the Media Library

Finally, we have to read to image we just save to isolated storage in order to get a Stream representation of it. This stream now can simply be stored to the device’s media library.

var fileStream = store.OpenFile(tempName, FileMode.Open, FileAccess.Read))
var library = new MediaLibrary();
var pic = library.SavePicture(fileName, fileStream);

Here is the whole code again as a handy extension method for the WriteableBitmap class.

public static void SaveToMediaLibrary(this WriteableBitmap wb, string fileName)
{
  var store = IsolatedStorageFile.GetUserStoreForApplication();
  // If a file with this name already exists, delete it.
  var tempName = Guid.NewGuid().ToString();
  using (var fileStream = store.CreateFile(tempName))
  {
    // Save the WriteableBitmap into isolated storage as JPEG.
    Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 100);
  }
  using (var fileStream = store.OpenFile(tempName, FileMode.Open, FileAccess.Read))
  {
    // Now, add the JPEG image to the photos library.
    var library = new MediaLibrary();
    var pic = library.SavePicture(fileName, fileStream);
  }
}

If we want to store a BitmapImage instead, we can simply create another extension method and reuse the existing functionality.

public static void SaveToMediaLibrary(this BitmapImage bmi, string fileName)
{
  new WriteableBitmap(bmi).SaveToMediaLibrary(fileName);
}

That was easy, right?