Wednesday, September 08, 2010

Advanced Silverlight bitmaps

Bitmap handling - using WriteableBitmap in particular differs greatly from WPF. In this article we look as the problems of loading bitmaps and generating them dynamically.
Bitmaps from streams
  Although a bitmap source seems only to be creatable from other bitmaps or UIElements you can in fact create a bitmap from any suitably formatted stream using the SetSource method.
The only real problem here is that the stream of bytes that you provided have to take the form of a valid jpeg, png or gif and this makes it difficult to convert a raw bit stream into a finished bitmap.
As a simple example, let’s use the OpenFileDialog to read in an image stored on the local machine. This has to be called from a button handler or some user initiated code otherwise you generate a security error. So add a button to and an image control to a new Silverlight project and:
using System.Windows.Media.Imaging;
using System.IO;
To create a stream we first use the OpenFileDialog:
private void button1_Click(object sender, RoutedEventArgs e)
{

OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "JPEG Files (*.jpg;*.jpeg)|*.jpg;*.jpeg | All Files (*.*)|*.*";
ofd.FilterIndex = 1;
bool?  result=ofd.ShowDialog();

Notice that we can’t use DialogResult as we would in WPF because Silverlight does things differently.
Read more: I Programmer