After processing is complete, the user is provided with the means to save the image via an application bar icon button. The page contains an ICommand
called SaveCommand
, as shown:
readonly ICommand saveCommand;
public ICommand SaveCommand
{
get
{
return saveCommand;
}
}
The command is instantiated in the constructor and when executed calls the page’s SaveImage
method, which is shown in the following excerpt:
public MainPage()
{
InitializeComponent();
saveCommand = new DelegateCommand(obj => SaveImage());
DataContext = this;
photoChooserTask.Completed += HandlePhotoChooserTaskCompleted;
}
The SaveImage
method retrieves the WriteableBitmap
from the Image
control and then uses the WriteableBitmap
extension method SaveJpeg
to write the image bytes to a MemoryStream
. The MemoryStream
is then passed to the MediaLibrary.SavePicture
method, as shown:
void SaveImage()
{
var writeableBitmap = (WriteableBitmap)image.Source;
if (writeableBitmap == null)
{
return;
}
const int jpegQuality = 90;
using (MemoryStream memoryStream = new MemoryStream())
{
writeableBitmap.SaveJpeg(
memoryStream,
writeableBitmap.PixelWidth, // target width
writeableBitmap.PixelHeight, // target height
0, // orientation.
jpegQuality);
memoryStream.Seek(0, SeekOrigin.Begin);
using (MediaLibrary mediaLibrary = new MediaLibrary())
{
Picture savedPicture
= mediaLibrary.SavePicture(imageName, memoryStream);
}
}
MessageBox.Show("Image saved to Saved Pictures.");
}
The MediaLibrary.SavePicture
method requires that the specified image name is not null or an empty string. The SavePicture
method has two overloads; one accepts a Stream
of image bytes, the other a byte array representing the image. Both save the image to the Saved Pictures album in the Pictures Hub.
The XAML for the MainPage
class contains an AppBarIconButton
with a binding to the SaveCommand
(see Listing 20.3). For more information on the custom AppBarIconButton
, see Chapter 8, “Taming the Application Bar.”
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<u:AppBar>
<u:AppBarIconButton
x:Name="button_Save"
Command="{Binding SaveCommand}"
Text="Save"
IconUri="/Images/appbar.save.rest.png" />
</u:AppBar>
<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
<TextBlock Text="Windows Phone Unleashed"
Style="{StaticResource PhoneTextNormalStyle}"/>
<TextBlock Text="extras" Margin="9,-7,0,0"
Style="{StaticResource PhoneTextTitle1Style}"/>
</StackPanel>
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<Image x:Name="image" />
<ProgressBar x:Name="progressBar" IsIndeterminate="True" />
</Grid>
</Grid>
When the SaveImage
method completes, a message is displayed informing the user that the image was successfully saved (see Figure 20.5).
18.222.116.146