Writing to SD cards

The final part of the project is writing the captured images to the SD card. You will notice that the camera_PictureCaptured method has a new line that assigns the image just taken to a member variable called lastPicture:

void camera_PictureCaptured(Camera sender, GT.Picture picture)
{
    imageDisplay.Background = new ImageBrush(picture.MakeBitmap());
    lastPicture = picture;
}

Now, whenever the main timer “ticks,” we will save the previous image before taking a new one:

void timer_Tick(GT.Timer timer)
{
    // save the last image captured.
    // The new one probably isn't ready yet
    SaveLastImage();
    if (camera.CameraReady)
    {
        camera.TakePicture();
    }
}

The actual writing to the SD card is all contained in the method SaveLastImage:

void SaveLastImage()
{
    if (lastPicture == null)
    {
        return;
    }
    try
    {
        String filename = "picture_" + pictureIndex + ".bmp";
        DisplayMessage("Saving .....");
        sdCard.GetStorageDevice().WriteFile(filename, lastPicture.PictureData);
        DisplayMessage("Photo Saved to: " + filename);
        pictureIndex++;
    }
    catch (Exception ex)
    {
        DisplayMessage("SD Card Error");
    }
}

First of all, this checks to see that there is an image to be saved. If there isn’t, it simply returns without doing anything.

If there is an image, then the remainder of the method is contained in a try / catch block. This ensures that if anything goes wrong in saving the image—for example, the SD card is not inserted or is full or write-protected—then a message will be displayed.

The first thing we do is construct ...

Get Getting Started with .NET Gadgeteer now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.