Tuesday, June 02, 2009

Loading BitmapImage from disk

While loading image in XAML is pretty easy (use <Image Source="xx.jpg"/>), it is not so straight forward to load an ImageSource from a file. (I always forget how to do this). So here is the code which might help you all. I have also specified some commented code which can be used to get thumbnails out of the image and other options like caching, etc.

ImageSource LoadImage(string filePath)
{
BitmapImage img = new BitmapImage();
try
{

img.BeginInit();
img.UriSource = new Uri(filePath, UriKind.RelativeOrAbsolute);
img.CacheOption = BitmapCacheOption.OnLoad;
//img.CreateOptions = BitmapCreateOptions.DelayCreation;
img.DecodePixelWidth = 50;
//img.DecodePixelHeight = 200;
img.EndInit();
}

catch
{
}
return img;

}

By the way, I have at last set up SyntaxHighlighter for my blog! this is sweet. Thanks to this post for the instructions.

No comments: