Click here to Skip to main content
15,905,593 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using System.Windows.Media.Imaging;

namespace WPF_LoginForm.Converter
{
    public class ByteToImageConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is byte[] byteArray)
            {
                var bitmapImage = new BitmapImage();
                using (var stream = new MemoryStream(byteArray))
                {
                    bitmapImage.BeginInit();
                    bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                    bitmapImage.StreamSource = stream;
                    bitmapImage.EndInit();
                }
                return bitmapImage;
            }
            return null;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

This is my Dashboard View
<pre><UserControl x:Class="WPF_LoginForm.Views.DashboardView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:WPF_LoginForm.Views"
             xmlns:viewModels="clr-namespace:WPF_LoginForm.ViewModels"
             xmlns:converter="clr-namespace:WPF_LoginForm.Converter"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800">

    

    <UserControl.DataContext>
        <viewModels:DashboardViewModel/>
    </UserControl.DataContext
        >
    <UserControl.Resources>
        <converter:ByteToImageConverter x:Key="ByteToImageConverter"/>
    </UserControl.Resources>

    <Border>
        <Border.Background>
            <LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
                <GradientStop Color="{StaticResource winBorderColor1}" Offset="0"/>
                <GradientStop Color="{StaticResource winBorderColor2}" Offset="0.75"/>
                <GradientStop Color="{StaticResource winBorderColor3}" Offset="1"/>
            </LinearGradientBrush>
        </Border.Background>
        <Grid>
            <TextBlock Text="DashBoardView"
                       Foreground="Black"
                       FontSize="50"
                       FontWeight="Medium"/>
            <Image Source="{Binding ProfilePicture, Converter={StaticResource 
                           ByteToImageConverter}}"
                  Stretch="Fill"/>
        </Grid>
    </Border>
</UserControl>

This is My Dashboard View Model
using System;
using System.ComponentModel;
using System.IO;
using System.Runtime.CompilerServices;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using WPF_LoginForm.Models;

namespace WPF_LoginForm.ViewModels
{
    public class DashboardViewModel : ViewModelBase
    {
        private byte[] _profilePicture;

        // Property for the profile picture byte array
        public byte[] ProfilePicture
        {
            get { return _profilePicture; }
            set
            {
                _profilePicture = value;
                OnPropertyChanged(nameof(ProfilePicture));
            }
        }
    }
}

My User Repositories
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using WPF_LoginForm.Models;

namespace WPF_LoginForm.Repositories
{
    public class UserRepository : RepositoryBase, IUserRepository
    {
        public void Add(UserModel userModel)
        {
            throw new NotImplementedException();
        }

        public bool AuthenticateUser(NetworkCredential credential)
        {
            bool validUser;
            using (var connection = GetConnection())
            using (var command = new SqlCommand())
            {
                connection.Open();
                command.Connection = connection;
                command.CommandText = "select *from [user] where username=@username and [password]=@password";
                command.Parameters.Add("@username", SqlDbType.NVarChar).Value = credential.UserName;
                command.Parameters.Add("@password", SqlDbType.NVarChar).Value = credential.Password;
                validUser = command.ExecuteScalar() == null ? false : true;
            }
            return validUser;
        }

        public void Edit(UserModel userModel)
        {
            throw new NotImplementedException();
        }
        public IEnumerable<UserModel> GetByAll()
        {
            throw new NotImplementedException();
        }
        public UserModel GetById(int id)
        {
            throw new NotImplementedException();
        }
        public UserModel GetByUsername(string username)
        {
            UserModel user = null;
            using (var connection = GetConnection())
            using (var command = new SqlCommand())
            {
                connection.Open();
                command.Connection = connection;
                command.CommandText = "select *from [user] where username=@username";
                command.Parameters.Add("@username", SqlDbType.NVarChar).Value = username;
                using (var reader = command.ExecuteReader())
                {
                    if (reader.Read())
                    {
                        user = new UserModel()
                        {
                            Id = reader[0].ToString(),
                            Username = reader[1].ToString(),
                            Password = string.Empty,
                            FirstName = reader[3].ToString(),
                            LastName = reader[4].ToString(),
                            EmailAddress = reader[5].ToString(),
                        };
                    }
                }
            }
            return user;
        }
        public UserAccountModel GetUserAccountByUsername(string username)
        {
            UserAccountModel userAccount = null;
            using (var connection = GetConnection())
            using (var command = new SqlCommand())
            {
                connection.Open();
                command.Connection = connection;
                command.CommandText = "SELECT username, DisplayName, ProfilePicture FROM [user] WHERE Username = @username";
                command.Parameters.Add("@username", SqlDbType.NVarChar).Value = username;
                using (var reader = command.ExecuteReader())
                {
                    if (reader.Read())
                    {
                        userAccount = new UserAccountModel()
                        {
                            Username = reader["username"].ToString(),
                            DisplayName = reader["DisplayName"].ToString(),
                            ProfilePicture = reader["ProfilePicture"] as byte[],
                            FirstName = reader["FirstName"].ToString(),
                            LastName = reader["LastName"].ToString()
                        };
                }
            }
        }
        return userAccount;
    }

        public void Remove(int id)
        {
            throw new NotImplementedException();
        }
    }
}
MyAccountModel
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WPF_LoginForm.Models
{
   public class UserAccountModel
    {
    public string Username { get; set; }
    public string DisplayName { get; set; }
    public byte[] ProfilePicture { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    }
}


What I have tried:

I have tried but nothing happened.

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
using System.Windows.Media.Imaging;

namespace WPF_LoginForm.Converter
{
    public class ByteToImageConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is byte[] byteArray)
            {
                var bitmapImage = new BitmapImage();
                using (var stream = new MemoryStream(byteArray))
                {
                    stream.Seek(0, SeekOrigin.Begin);
                    bitmapImage.BeginInit();
                    bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                    bitmapImage.StreamSource = stream;
                    bitmapImage.EndInit();
                }
                return bitmapImage;
            }
            return null;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

I also did the bind correctly. Or did I?
trol x:Class="WPF_LoginForm.Views.DashboardView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:WPF_LoginForm.Views"
             xmlns:viewModels="clr-namespace:WPF_LoginForm.ViewModels"
             xmlns:converter="clr-namespace:WPF_LoginForm.Converter"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800">

    

    <UserControl.DataContext>
        <viewModels:DashboardViewModel/>
    </UserControl.DataContext
        >
    <UserControl.Resources>
        <converter:ByteToImageConverter x:Key="ByteToImageConverter"/>
    </UserControl.Resources>

    <Border>
        <Border.Background>
            <LinearGradientBrush StartPoint="0,0" EndPoint="1,1">
                <GradientStop Color="{StaticResource winBorderColor1}" Offset="0"/>
                <GradientStop Color="{StaticResource winBorderColor2}" Offset="0.75"/>
                <GradientStop Color="{StaticResource winBorderColor3}" Offset="1"/>
            </LinearGradientBrush>
        </Border.Background>
        <Grid>
            <TextBlock Text="DashBoardView"
                       Foreground="Black"
                       FontSize="50"
                       FontWeight="Medium"/>
            <Image Source="{Binding ProfilePicture, Converter={StaticResource 
                           ByteToImageConverter}}"
                  Stretch="Fill"/>
        </Grid>
    </Border>
</UserControl>
Posted
Updated 24-Apr-24 23:40pm
v3

1 solution

It's been a while since I've done this but I'm pretty sure you are going to have to do stream.Seek(0, SeekOrigin.Begin); once you instantiate it.
 
Share this answer
 
Comments
Ignatius Baron Rio 25-Apr-24 5:42am    
I tried but still nothing happened. See "my what I have tried" section if i had done it correctly. Thanks
Pete O'Hanlon 8-May-24 0:22am    
You are disposing your memory stream before you leave the converter method. Unsurprisingly, this disposes the image information. Just after you call EndInit();, call Freeze(); on your image to freeze the underlying image. This makes your image immutable.
Ignatius Baron Rio 8-May-24 6:24am    
Thank you for your help it works.
Pete O'Hanlon 8-May-24 7:14am    
That's excellent news. I'm glad it's working for you now.
Ignatius Baron Rio 14-May-24 13:51pm    
Yes. Programming can be frustrating when you are a beginner. I also have another question on my profile https://www.codeproject.com/Questions/5382337/How-do-I-display-the-button-function-from-my-drink. I can't seem to make a function from one form to another.

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