umesh hb
umesh hb

Reputation: 39

How do I convert a System.Drawing.Image to a WPF Image

Dim classSymbol As Byte() = ConvertBase64ToByteArray(CheckSheetDetailObj.ClassSymbol)
Dim myimage As System.Drawing.Image
Dim ms As System.IO.MemoryStream = New System.IO.MemoryStream(classSymbol)
myimage = System.Drawing.Image.FromStream(ms)

I need to convert myimage which is of type System.Drawing.Image to System.Windows.Control.Image

Upvotes: 0

Views: 369

Answers (1)

Jimi
Jimi

Reputation: 32288

If you want to create a graphic object from a byte array encoded as Base64, then assign the resulting bitmap to a WPF Image Control, you just need a MemoryStream.
You don't need to add a reference to System.Drawing at all.

In any case, you don't convert a graphic object to a Control, you assign a graphic object to a Control that can present bitmap graphic contents.

You can generate a new BitmapImage, set its BitmapImage.StreamSource to a MemoryStream object and assign the BitmapImage to an Image Control's Source Property:

SomeImage.Source = BitmapImageFromBase64([Some Base64 string])

' [...]

Private Function BitmapImageFromBase64(base64 As String) As BitmapImage
    Dim bitmap = New BitmapImage()
    bitmap.BeginInit()
    bitmap.CacheOption = BitmapCacheOption.OnLoad
    bitmap.StreamSource = New MemoryStream(Convert.FromBase64String(base64))
    bitmap.EndInit()
    Return bitmap
End Function

If you don't have an existing Image Control, you can create one on the fly, then add it to a Container.
For example, a WrapPanel:

Dim newImage As New Image With {
    .Source = BitmapImageFromBase64([Some Base64 string]),
    .Width = 100,
    .Height = 100,
    .Margin = New Thickness(5, 5, 0, 0)
}
' Of course use the reference of an existing WrapPanel
wrapPanel.Children.Add(newImage)

Upvotes: 1

Related Questions