Click here to Skip to main content
14,982,875 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have base64 formatted string.
I want to display that base64 string into image in WPF.

I tried the below code. but after run this code no errors.
but image not shown.

please give me a solution for this problem.

What I have tried:

xaml

<Image x:Name="img1"  Height="20" Width="20" Source="{Binding ImgSource}"/>


codebehind
dim ImgSource as Image

Dim binaryData As Byte() = Convert.FromBase64String(base64string)
Dim bi As BitmapImage = New BitmapImage()
bi.BeginInit()
bi.StreamSource = New MemoryStream(binaryData)
bi.EndInit()

Dim img As Image = New Image()
img.Source = bi

ImgSource = img
Posted
Updated 9-Jun-21 4:49am

1 solution

Check the output window in Visual Studio for runtime data binding errors.

There are two problems with the code you've shown:

1) You've declared the ImgSource variable as either a local variable, or a field. WPF binding only works with properties.

2) Since you're binding to something defined in your code-behind, you need to set the DataContext to the class instance which contains the property, either on the image itself, or somewhere higher up in the logical tree. The usual approach is to do that in the constructor.

VB.NET
Public Partial Class Window1 : Window
    Public Sub New()
        InitializeComponent()
        DataContext = Me
        
        Dim base64string As String = ...
        
        Dim bi As New BitmapImage()
        bi.BeginInit()
        bi.StreamSource = New MemoryStream(Convert.FromBase64String(base64String))
        bi.EndInit()
        
        Dim img As New Image()
        img.Source = bi
        ImgSource = img
    End Sub
    
    Public ReadOnly Property ImgSource As Image
End Class
   
Comments
shiva_yn 11-Jun-21 6:54am
   
your answer is wright..but i changed this line its works fine.
Dim img As New ImageSource()

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900