Quick and painless Byte Array to Image converter for RadGridView for Silverlight

Posted by: the telerik blogs, on 13 Oct 2009 | View original | Bookmarked: 0 time(s)

We received a question today in regards to a binding issue with RadGridView, or rather an issue with an Image in a custom cell template that the customer was trying to bind to a custom value. They had the basic setup right:

<DataTemplate> <Image Source="{Binding ImageData}" /> </DataTemplate>

But something wasn't quite working right. After doing a little digging, we found that they weren't sending a URI to the Image but rather a byte array. Unfortunately, the Image control in Silverlight doesn't quite know how to pick up on this so you need to convince it- with a converter.

With a little bit of coding magic, and knowledge of how the Image control works, we came up with the following:

public class ByteArrayToImageConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { byte[] byteBlob = value as byte[]; MemoryStream ms = new MemoryStream(byteBlob); BitmapImage bmi = new BitmapImage(); bmi.SetSource(ms); return bmi; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } }

Since the Image control allows you to use a BitmapImage as an ImageSource, this turns that byte array into a BitmapImage and returns it to the custom cell template in RadGridView. The new datatemplate only requires a minor modification:

<DataTemplate> <Image Source="{Binding ImageData, Converter={StaticResource ByteToImageConverter}}" /> </DataTemplate>

And you're all set. Just so you can see it in action, here is a sample projectwith the converter working. I threw a few sample pictures into the default website Images folder for you to play with.

Happy coding!

Category: GridView | Other Posts: View all posts by this blogger | Report as irrelevant | View bloggers stats | Views: 5164 | Hits: 48

Similar Posts

  • Cross domain request in Silverlight 2.0 beta 2 more
  • Getting Images to render properly in the ASP.NET Designer more
  • JavaScript Revisited: Image Gallery more
  • Looking Forward to next AjaxPro Release more
  • Lesser known CS goodies: ImageInfo class more
  • from worst practice, images and databases more
  • Generate thumbnails via your images more

News Categories

.NET | Agile | Ajax | Architecture | ASP.NET | BizTalk | C# | Certification | Data | DataGrid | DataSet | Debugger | DotNetNuke | Events | GridView | IIS | Indigo | JavaScript | Mobile | Mono | Patterns and Practices | Performance | Podcast | Refactor | Regex | Security | Sharepoint | Silverlight | Smart Client Applications | Software | SQL | VB.NET | Visual Studio | W3 | WCF | WinFx | WPF | WSE | XAML | XLinq | XML | XSD