Sunday, November 23, 2008

WPF BitMapImage Converters and SQL Image

Learning in progress.

For obvious reasons, there are developers needs to save the images
whether .jpg or .png to backend, specifically to MS SQL image type.

WPF can handle both retrieving and saving of Images through converters.

TO DISPLAY
Let us assume that you use DataTemplate to display your image as part
of our listview columns.

-- on window resources / or app resources
declare the template for the image and this will be part of listview's column


<DataTemplate key="TemplatePic">
<Image Name="myImage" Source="{Binding Path=EmployeePic, Converter="{StaticResource ByteToImageConverter}} />
</DataTemplate>



-- on ListView, define the template for the gridview column


<Listview name="ListView1">
<ListView.view>
<GridView>
<GridViewColumn header="Image" name="myPicture" celltemplate="{StaticResource TemplatePic}">
<GridView>
</ListView.View>

--for your converter resource class

Public Class ByteToImageConverter
Implements IValueConverter


Public Function Convert(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert
If value Is Nothing Then
Return Nothing
End If
Dim picByte As Byte() = value
Dim bi As BitmapImage = New BitmapImage()
bi.BeginInit()
Dim ImageStream As IO.Stream = New IO.MemoryStream(picByte)
bi.StreamSource = ImageStream
bi.EndInit()
Return bi
End Function


Public Function ConvertBack(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack

>
    Dim rtb = New RenderTargetBitmap(value.Width, value.Width, 92, 92, PixelFormats.Pbgra32)
    rtb.Render(value)
    Dim enc = New System.Windows.Media.Imaging.PngBitmapEncoder()
    enc.Frames.Add(System.Windows.Media.Imaging.BitmapFrame.Create(rtb))
    ' array of byte for the image
    Dim mPicBtye As Byte() = Nothing
    Using mMemStream As IO.MemoryStream = New IO.MemoryStream
    enc.Save(mMemStream)
    mPicBtye = mMemStream.ToArray
    End Using
Return mPicBtye

End Function
End Class




In the Convert() function converts the "value" from byte() to a BitMapImage using IO.Stream. This reads the value saved from the backend and convert it to the memory stream of byte.

The ConvertBack() function is a reverse process wherein we have converted the BitMapImage back to Byte().

The example above is very traditional but uses memory stream to convert the image.

Hope you like it.

2 comments:

Unknown said...

How can I do that on c#

Gio said...

Hi,

Sorry for not answering immediately.
It is only straight forward conversion.

You could also copy and paste the code above and convert it to c# in this site.

http://www.developerfusion.com/tools/convert/csharp-to-vb/