Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
391 views
in Technique[技术] by (71.8m points)

c# - Bind base64 string to listview in xamarin form

First of all I am new in Xamarin.Form. I am trying to get best from Google but some of functionality I am not able to get even searched a lot.

I am creating a Xamarin.Form app. In that app, I am storing the image to base64 string format in sql server and my data type in sql server is varchar(Max).

My issue is that, How can I convert the base64 string to an image and also with bind the image to list view.

Code of Listview:

<ListView x:Name="listView" HasUnevenRows="true" SeparatorColor="Gray">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <Image Source="{Binding image}"  Grid.Row="0" 
                        Grid.RowSpan="3" Grid.Column="0" 
                        HorizontalOptions="Center" HeightRequest="50" 
                        VerticalOptions="Center">
                    <Image.GestureRecognizers>
                        <TapGestureRecognizer Tapped="OnImageTapped" />
                    </Image.GestureRecognizers>
                </Image>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

Code of c#:

Public async Task loadDeveloperList()
{
    try
    {            
        List<employee> employeeDetail = new List<employee>();

        HttpClient client = new HttpClient();
        StringBuilder sb = new StringBuilder();
        client.MaxResponseContentBufferSize = 256000;
        var RestUrl = "http://example.com/Getemployee/";
        var uri = new Uri(RestUrl);
        actIndicator.IsVisible = true;
        actIndicator.IsRunning = true;
        var response = await client.GetAsync(uri);

        if (response.IsSuccessStatusCode)
        {
            var content = await response.Content.ReadAsStringAsync();

            List<employee> onjEmployee = JsonConvert.DeserializeObject<List<employee>>(content);

            foreach (var item in onjEmployee)
            {
                employee emptemp = new employee()
                {
                    empID = item.empID,
                    name = item.name,
                    city = item.city,
                    post = item.post,
                    salary = item.salary,
                    gender = item.gender,
                    image = item.image                            
                };
                string cFotoBase64 = emptemp.image;
                byte[] ImageFotoBase64 = System.Convert.FromBase64String(cFotoBase64);

                employeeDetail.Add(emptemp);                                         
            }
            listView.ItemsSource = employeeDetail;
        }
    }
    catch (Exception ex)
    {

    }          
}

So any one please suggest me a idea and any solution.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As per this forum thread you could create a converter for it. Just keep the Base64 string as part of your Employee i.e. in the Base64Image property.

Now define a converter like this.

public class ConverterBase64ImageSource : IValueConverter
{
    public object Convert (object value, Type targetType, object parameter, CultureInfo culture)
    {
        string base64Image = (string)value;

        if (base64Image == null)
            return null;

        // Convert base64Image from string to byte-array
        var imageBytes = System.Convert.FromBase64String(base64Image);

        // Return a new ImageSource
        return ImageSource.FromStream (() => {return new MemoryStream(imageBytes);});
    }

    public object ConvertBack (object value, Type targetType, object parameter, CultureInfo culture)
    {
        // Not implemented as we do not convert back
        throw new NotSupportedException();
    }
}

Now in your XAML declare and use the converter like this:

Add the namespace to the page root, I'm going to assume it's a normal ContentPage, so it should look something like:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:YourApp;assembly=YourApp"
             x:Class="YourApp.YourPage">

Note that YourApp and YourPage, etc. should be replaced with your actual app name and the right namespaces.

Now declare the converter as part of your page.

<ContentPage.Resources>
   <ResourceDictionary>
      <local:ConverterBase64ImageSource x:Key="Base64ToImageConverter" />
   </ResourceDictionary>
</ContentPage.Resources>

Finally use the converter on the Image.

<ListView x:Name="listView" HasUnevenRows="true" SeparatorColor="Gray">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <Image Source="{Binding Base64Image, Converter={StaticResource Base64ToImageConverter}}}"  Grid.Row="0" 
                        Grid.RowSpan="3" Grid.Column="0" 
                        HorizontalOptions="Center" HeightRequest="50" 
                        VerticalOptions="Center">
                    <Image.GestureRecognizers>
                        <TapGestureRecognizer Tapped="OnImageTapped" />
                    </Image.GestureRecognizers>
                </Image>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

Your images should now be shown!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...