Click here to Skip to main content
Click here to Skip to main content

Saving Bitmaps to Isolated Storage in Silverlight 3

By , 31 Jul 2009
Rate this:
Please Sign up or sign in to vote.

There may be times when you wish to save a bitmap image to the user's local storage. Perhaps it was a generated image that is used in the application, or maybe it is an externally referenced image that you are loading locally for caching purposes. I found many examples online of generating a "save dialog" box, but none for saving it.

This is a very bare bones application that demonstrates how to save the image. This is in no industry-standard format - it literally writes out the size of the image in pixels (height, width), then streams out the bytes for alpha, red, green, and blue. It is meant as a foundation to better understand how to get the image data and manipulate it. Once you "know" the pixels, then you can easily start to apply more advanced algorithms like BMP, PNG, JPG, or even GIF to save and retrieve the data.

Here is the XAML - you can create a new Silverlight Application and literally plop in the XAML and code-behind to get started:

<UserControl x:Class="BitmapSaver.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d=http://schemas.microsoft.com/expression/blend/2008 
	xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">
  <Grid x:Name="LayoutRoot">
        <Grid.RowDefinitions>
            <RowDefinition Height="30"></RowDefinition>
            <RowDefinition Height="30"></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>
        <Canvas HorizontalAlignment="Left" x:Name="CanvasSource"
		Height="20" Width="100" Grid.Row="0">
                <TextBlock FontSize="14" VerticalAlignment="Center" 
		HorizontalAlignment="Center" Width="Auto" Height="Auto" 
		Foreground="Red" FontWeight="Bold" Text="BitMapExample"/>             
        </Canvas>
        <Image HorizontalAlignment="Left" x:Name="BitmapImageRef" Stretch="None" 
		Grid.Row="1"/>
        <TextBlock x:Name="Status" Text="Processing..." Grid.Row="2"/>        
  </Grid>
</UserControl>

In the XAML, there is a grid with three rows. The first is a canvas with red text inside it. This is what we'll turn into a bitmap image and save. The second row is an image "placeholder" for the image that we process. The final row is a simple text block to update the status.

Here is the code-behind:

public partial class MainPage
{
    private const string SAVEDIMG = "SavedBitmapImage.xyz";
        
    /// <span class="code-SummaryComment"><summary>
</span>    ///     Default constructor
    /// <span class="code-SummaryComment"></summary>
</span>    public MainPage()
    {
        InitializeComponent();
        CanvasSource.Loaded += _MainPageLoaded;
    }

    /// <span class="code-SummaryComment"><summary>
</span>    ///     Canvas loaded
    /// <span class="code-SummaryComment"></summary>
</span>    /// <span class="code-SummaryComment"><param name="sender"></param />
</span>    /// <span class="code-SummaryComment"><param name="e"></param />
</span>    void _MainPageLoaded(object sender, RoutedEventArgs e)
    {
        Status.Text = "Checking disk...";
        byte[] buffer = _LoadIfExists(SAVEDIMG); 

        if (buffer.Length >

The main process simply waits for the canvas to be loaded.

We check if the image is saved in isolated storage. If it exists, we render it and attach it to the image. If not, we render it based on the canvas in the first row and then save it.

_LoadIfExists is a basic routine that checks for a file's existence and if it is there, loads it into a byte buffer and returns it. If the file is not there, it returns an empty byte array.

_SaveToDisk takes a byte array and persists it to isolated storage. Possible enhancements to this routine include checking to see if the available storage exists and prompting the user to extend it if needed, as well as organizing files into subdirectories and checking for/creating those as well.

_GetSaveBuffer takes the bitmap and returns a buffer of bytes. The first two bytes are the width, the second two the height, and finally the remaining bytes contain the alpha, red, green, and blue channels for each pixel in the bitmap. Obviously this is where you can conform to any one of the graphics standards available and supply your own compression.

_GetImage takes the buffer for an image saved in the previous format, and renders it to the bitmap so it can be displayed.

The idea behind this example is to run in debug and step through to see. The first time you run it, it will simply copy the image (the text in this case) and display it as well as save it to isolated storage. Any subsequent run will load it from storage and show it unless you clear storage or change the file name.

Again, this is just a basic introduction to manipulating and saving bitmaps in isolated storage.

Jeremy Likness

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Jeremy Likness
Architect Wintellect
United States United States
Jeremy Likness is a principal consultant at Wintellect. Jeremy, an experienced entrepreneur and technology executive, has successfully helped ship commercial enterprise software for 20 years. He specializes in catalyzing growth, developing ideas and creating value through delivering software in technical enterprises. His roles as business owner, technology executive and hands-on developer provided unique opportunities to directly impact the bottom line of multiple businesses by helping them grow and increase their organizational capacity while improving operational efficiency. He has worked with several initially small companies like Manhattan Associates and AirWatch before they grew large and experienced their transition from good to great while helping direct vision and strategy to embrace changing technology and markets. Jeremy is capable of quickly adapting to new paradigms and helps technology teams endure change by providing strong leadership, working with team members “in the trenches” and mentoring them in the soft skills that are key for engineers to bridge the gap between business and technology.
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
GeneralMy vote of 5 Pinmemberviragdesai25-Sep-12 18:04 
GeneralMy vote of 1 PinmemberMember 829288310-Oct-11 13:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140415.2 | Last Updated 31 Jul 2009
Article Copyright 2009 by Jeremy Likness
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid