Bitmaps are generally implemented as immutable objects in WPF. What this means is that once you create a bitmap you can't make any changes to it. You can manipulate bitmaps by creating new versions, which then immediately become immutable and sometimes this is a good way to work. Immutable bitmaps can be very efficient unless you want to indulge in a lot of dynamic changes in which case the overhead of creating and destroying them rapidly becomes too expensive. In this situation you need something a little more flexible - the WriteableBitmap. The WriteableBitmap, as its name suggests, isn't immutable and you can get at its individual pixels and manipulate them as much as you want. This is the ideal way to work when you need dynamic bitmaps. So let’s take a look at WriteableBitmap, how it works and how to use it to do dynamic things. Notice that the WriteableBitmap class in Silverlight is very different to the same class in WPF. To use WriteableBitmap we need to add:
using System.Windows.Media.Imaging;
which contains all of the additional bitmap facilities we need. You can create a WriteableBitmap in two ways. The most commonly used is to simply specify the size and format of the bitmap:
WriteableBitmap wbmap = new
WriteableBitmap(100, 100, 300,
300, PixelFormats.Bgra32, null);
This specifies a WriteableBitmap 100 by 100 pixels with a resolution of 300dpi by 300 dpi using a Bgra32 pixel format. Each pixel, a 32-bit int, uses a four-byte BGRA – that is the pixel is made up of a byte giving the Blue, Green, Red and Alpha values. The final parameter is used to specify a palette if the format needs one. You can specify a wide range of formats for the bitmap you create and in each case each pixel takes a given number of bits to represent and you need to find out how the bits allocated to each pixel determine its colour. The second method of creating a WriteableBitmap is to base it on an existing BitmapSource or derived class. For example, you should be able to create a WriteableBitmap from a standard bitmap using the constructor: WriteableBitmap(bitmapsource); but if you try this with a BitmapImage loaded from a URI you will get a null object error. The reason is that the bitmap might not yet be downloaded. For a local file the bitmap load blocks execution until it is loaded:
Uri uri = new Uri(@"pack://application:
,,,/Resources/mypic.jpg");
BitmapImage bmi = new BitmapImage(uri);
WriteableBitmap bmi2 = new
WriteableBitmap(bmi);
image1.Source = bmi2;
In this case the WriteableBitmap is created with no problems. If the URI was an HTTP URL, however, the load would not block the execution and the result would be an error.