If you read my previous post about WP7, explaining how to use launchers and choosers, you may wonder how to capture an image using the phone camera, then saving it to the phone’s isolated storage.
While it is easy to capture an image, it’s trickier to save it to the isolated storage.
To capture an image you should do this:
public partial class MainPage : PhoneApplicationPage
{
private byte[] _imageBytes;
private void buttonCapture_Click(object sender, RoutedEventArgs e)
{
ShowCameraCaptureTask();
}
private void ShowCameraCaptureTask()
{
var cameraTask = new CameraCaptureTask();
cameraTask.Completed += cameraTask_Completed;
cameraTask.Show();
}
private void cameraTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
// Get the image temp file from e.OriginalFileName.
// Get the image temp stream from e.ChosenPhoto.
// Don't keep either the stream or rely on the temp
// file name as they may be vanished!
// Store the image bytes.
_imageBytes = new byte[e.ChosenPhoto.Length];
e.ChosenPhoto.Read(_imageBytes, 0, _imageBytes.Length);
// Seek back so we can create an image.
e.ChosenPhoto.Seek(0, SeekOrigin.Begin);
// Create an image from the stream.
var imageSource = PictureDecoder.DecodeJpeg(e.ChosenPhoto);
image.Source = imageSource;
}
}
}
Having the captured image bytes, lets see how to save the image in the Isolated Storage.
private void SaveToLocalStorage(string imageFileName, string imageFolder)
{
if (_imageBytes == null)
{
return;
}
var isoFile = IsolatedStorageFile.GetUserStoreForApplication();
if (!isoFile.DirectoryExists(imageFolder))
{
isoFile.CreateDirectory(imageFolder);
}
string filePath = Path.Combine(imageFolder, imageFileName);
using (var stream = isoFile.CreateFile(filePath))
{
stream.Write(_imageBytes, 0, _imageBytes.Length);
}
}
Now that you’ve saved the captured image in the iso storage, let’s see how to load it from there:
private void LoadFromLocalStorage(string imageFileName, string imageFolder)
{
var isoFile = IsolatedStorageFile.GetUserStoreForApplication();
if (!isoFile.DirectoryExists(imageFolder))
{
isoFile.CreateDirectory(imageFolder);
}
string filePath = Path.Combine(imageFolder, imageFileName);
using (var imageStream = isoFile.OpenFile(
filePath, FileMode.Open, FileAccess.Read))
{
var imageSource = PictureDecoder.DecodeJpeg(imageStream);
image.Source = imageSource;
}
}
You can download the code from here.