Code:
public static void SaveToMediaLibrary(
FrameworkElement element,
string title)
{
try
{
var bmp = new WriteableBitmap(element, null);
var ms = new MemoryStream();
bmp.SaveJpeg(
ms,
(int)element.ActualWidth,
(int)element.ActualHeight,
0,
100);
ms.Seek(0, SeekOrigin.Begin);
var lib = new MediaLibrary();
var filePath = string.Format(title + ".jpg");
lib.SavePicture(filePath, ms);
MessageBox.Show(
"Saved in your media library!",
"Done",
MessageBoxButton.OK);
}
catch
{
MessageBox.Show(
"There was an error. Please disconnect your phone from the computer before saving.",
"Cannot save",
MessageBoxButton.OK);
}
}
This method can save any FrameworkElement. Typically I use it to save a whole page, but you can pass any other element to it.
On line 7, we create a new WriteableBitmap. This excellent class can render a visual tree into a bitmap. Note that for even more features, you can use the great WriteableBitmapEx class library (which is open source).
On lines 9 to 16, we save the WriteableBitmap to a MemoryStream. The only format supported by default is JPEG, however it is possible to convert to other formats with the ImageTools library (also open source).
Lines 18 to 20 save the picture to the Windows Phone device’s media library.