Windows Phone 7 - Saving a Screen Grab to the Saved Pictures Library

27 September 2010

There are some examples around of how to work with the WP7 camera apis, but I just wanted a nice and easy way of allowing the user to take a screen grab of the current game screen in my WP7 app.

This is nice code to hook off a ‘Save Screen’ app bar menu item for example.

Firstly, ensure you have explicitly requested permission to use the media library in your WMAppManifest.xml file, otherwise you will get nasties.

    <Capability Name="ID_CAP_MEDIALIB"/>

All you need to do is pass in the UIElement representing your screen (e.g. commonly a LayoutRoot Grid for example). I’ve hard coded the height, width and quality of the image, adjust as required.

public void ScreenGrab(UIElement screen)
    String gameScreenFileName = "GameScreen.jpg";
    using (IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication())
        if (iso.FileExists(fileName))
        IsolatedStorageFileStream myFileStream = iso.CreateFile(gameScreenFileName);
        WriteableBitmap wb = new WriteableBitmap(480, 800);
        wb.Render(screen, null);
        System.Windows.Media.Imaging.Extensions.SaveJpeg(wb, myFileStream, wb.PixelWidth, wb.PixelHeight, 0, 100);
        myFileStream = iso.OpenFile(gameScreenFileName, FileMode.Open, FileAccess.Read);
        myFileStream.Seek(0, SeekOrigin.Begin);
        MediaLibrary library = new MediaLibrary();
        var savedPicName = String.Format("AlphaJax_{0}.jpg", Guid.NewGuid().ToString());
        Picture pic = library.SavePicture(savedPicName, myFileStream);
Want to get started?

We would love to help with your next app or game, please do get in touch.