How to: Encode a JPEG for Windows Phone and Save to the Pictures Library
March 22, 2012
This topic shows you how to encode a WriteableBitmap object to a JPEG stream, and add it to the pictures library on your Windows Phone. The following tasks are performed:
Add appropriate namespaces and create the design surface for the sample.
Encode a WriteableBitmap object to a JPEG file.
Add the JPEG to the pictures library on the Windows Phone.
Important Note: |
|---|
For the current release of the Windows Phone, the emulator does not support the viewing of photos in the Pictures Hub. You can view the photo created from this exercise only on a physical device. |
To begin, you need to create a new project and add the necessary namespaces.
Note:
|
|---|
|
The steps in the following procedure are for Visual Studio 2010 Express for Windows Phone. You may see some minor variations in menu commands or window layouts when you are using the add-in for Visual Studio 2010 Professional or Visual Studio 2010 Ultimate. This topic is based on C# development; however, Visual Basic code is also provided. |
To create a new project and add namespaces
-
In Visual Studio 2010 Express for Windows Phone, create a new project by selecting the File | New Project menu command.
-
The New Project window is displayed. Expand the Visual C# templates, and then select the Silverlight for Windows Phone templates.
-
Select the Windows Phone Application template. Fill in the Name box with a name of your choice.
-
Click OK. The New Windows Phone Application window is displayed.
-
In the Target Windows Phone Version menu, ensure that Windows Phone 7.1 is selected.
-
Click OK. A new project is created, and MainPage.xaml is opened in the Visual Studio designer window.
-
From the Project menu, select Add Reference. In the .NET tab, choose Microsoft.Xna.Framework, and click OK.
-
Open the code-behind file for the main page, MainPage.xaml.cs, and add the following directives at the top of the page.
To create the design surface
-
On MainPage.xaml, replace the Grid named LayoutRoot with the following code.
<!--LayoutRoot is the root grid where all page content is placed. --> <Grid x:Name="LayoutRoot" Background="Transparent"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <!--TitlePanel contains the name of the application and page title. --> <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28"> <TextBlock x:Name="ApplicationTitle" Text="PHOTOS" Style="{StaticResource PhoneTextNormalStyle}"/> <TextBlock x:Name="PageTitle" Text="encode" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/> </StackPanel> <!--ContentPanel - place additional content here. --> <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> <Image Height="395" HorizontalAlignment="Left" Margin="6,6,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Top" Width="444" Source="TestImage.jpg"/> <RadioButton Content="camera roll" Height="72" HorizontalAlignment="Center" Margin="96,407,90,0" Name="radioButtonCameraRoll" VerticalAlignment="Top" Width="270" GroupName="AlbumGroup"/> <RadioButton Content="saved pictures" Height="72" HorizontalAlignment="Right" Margin="0,453,90,0" Name="radioButtonSavedPictures" VerticalAlignment="Top" Width="270" GroupName="AlbumGroup"/> <Button Content="Save" Height="70" HorizontalAlignment="Center" Margin="6,519,0,0" Name="btnSave" VerticalAlignment="Top" Width="269" Click="btnSave_Click" /> </Grid> </Grid>
Note:The preceding code creates an image control that occupies the top to mid-portion of the page and a button control named btnSave. The orientation of these controls can be seen in the following illustration.
In this section, you add code to the btnSave click event handler to encode a WriteableBitmap object into a JPEG stream, and add it to the pictures library on the Windows Phone.
To encode a JPEG file and add it to the library
-
Add any JPEG file to your project through Solution Explorer. You can simply drag the photo over to the project name to add. For this example, the TestImage.jpg file was used. Make sure that you are aware of its path location in the project. In the MainPage.xaml file, add the following attribute and value to the Image control named image1.
Source=”TestImage.jpg”
Note:TestImage.jpg is just an example. Instead of TestImage.jpg, specify the name of the JPEG file that you added to the project.
After you add the attribute, the image1 control should look like this.
<Image Height="395" HorizontalAlignment="Left" Margin="6,6,0,0" Name="image1" Stretch="Fill" VerticalAlignment="Top" Width="468" Source="TestImage.jpg"/> -
In the MainPage.xaml.cs file, add the following code in the MainPage constructor, just below the InitializeComponent method call. This selects the camera roll album as the default storage location for the image.
-
Double-click the btnSave button in MainPage.xaml to add an event handler for the click event. The MainPage.xaml.cs file will open.
-
In the MainPage.xaml.cs file, replace the btnSave_Click method with the following code. Within this code, replace [Application Name] with the name of the project. For example, if your project is named CameraEncode and the image is named TestImage.jpg, the first parameter for the new Uri should be "CameraEncode;component/TestImage.jpg".
private void btnSave_Click(object sender, RoutedEventArgs e) { // Create a file name for the JPEG file in isolated storage. String tempJPEG = "TempJPEG"; // Create a virtual store and file stream. Check for duplicate tempJPEG files. var myStore = IsolatedStorageFile.GetUserStoreForApplication(); if (myStore.FileExists(tempJPEG)) { myStore.DeleteFile(tempJPEG); } IsolatedStorageFileStream myFileStream = myStore.CreateFile(tempJPEG); // Create a stream out of the sample JPEG file. // For [Application Name] in the URI, use the project name that you entered // in the previous steps. Also, TestImage.jpg is an example; // you must enter your JPEG file name if it is different. StreamResourceInfo sri = null; Uri uri = new Uri("[Application Name];component/TestImage.jpg", UriKind.Relative); sri = Application.GetResourceStream(uri); // Create a new WriteableBitmap object and set it to the JPEG stream. BitmapImage bitmap = new BitmapImage(); bitmap.CreateOptions = BitmapCreateOptions.None; bitmap.SetSource(sri.Stream); WriteableBitmap wb = new WriteableBitmap(bitmap); // Encode the WriteableBitmap object to a JPEG stream. wb.SaveJpeg(myFileStream, wb.PixelWidth, wb.PixelHeight, 0, 85); myFileStream.Close(); // Create a new stream from isolated storage, and save the JPEG file to the media library on Windows Phone. myFileStream = myStore.OpenFile(tempJPEG, FileMode.Open, FileAccess.Read); // Save the image to the camera roll or saved pictures album. MediaLibrary library = new MediaLibrary(); if (radioButtonCameraRoll.IsChecked == true) { // Save the image to the camera roll album. Picture pic = library.SavePictureToCameraRoll("SavedPicture.jpg", myFileStream); MessageBox.Show("Image saved to camera roll album"); } else { // Save the image to the saved pictures album. Picture pic = library.SavePicture("SavedPicture.jpg", myFileStream); MessageBox.Show("Image saved to saved pictures album"); } myFileStream.Close(); } -
Run the application by selecting the Debug | Start Debugging menu command. This will open the emulator window and launch the application. When you tap the Save button, your JPEG file will be saved in the Pictures hub to the Camera Roll or Saved Pictures album, depending on the radio button selection.
Important Note:
To view the saved picture, you must view it on a physical device. The emulator does not support picture browsing in this release.
The following example illustrates the completed application.