Friday, November 5, 2010

Bitmaps in WPF, disposing of bitmaps in WPF and other issues

The first thing is in WPF you can't set the Source of an Image Control to that of a Bitmap, you need to use the BitmapImage
This gives you a build error:
Image I = new Image(@"C:\Users\Public\Pictures\Sample Pictures\Penguins.bmp");
Imagecontrol.Image.Source = I
But this works:
Image I = new Image();
BitmapImage bi = new BitmapImage();
bi.UriSource = new Uri(@"C:\Users\Public\Pictures\Sample Pictures\Penguins.bmp", UriKind.Absolute);
Imagecontrol.Image.Source  = bi;
The problem with the above code is that whenever I used it and subsequently tried to delete the file Penguins.jpg or move it, I got an exception.  It seems like we were holding a lock on the file.  So the fix was to do the following:

      Imagecontrol.Image.Source = LoadImage(@"C:\Users\Public\Pictures\Sample Pictures\Penguins.bmp");

      private BitmapImage LoadImage(string myImageFile)
            BitmapImage myRetVal = null;
            if (myImageFile != null)
                BitmapImage image = new BitmapImage();
                using (FileStream stream = File.OpenRead(myImageFile))
                    image.CacheOption = BitmapCacheOption.OnLoad;
                    image.StreamSource = stream;
                myRetVal = image;
            return myRetVal;

No comments: