Listbox image control binding with SQLite , Image

2019-09-01 07:25发布

问题:

I have stored image bytes in SQLite database . when I want to get single image then I got that by id and convert image bytes to bitmap image. But when i want to bind list of data to listBox then I'm not able to bind directly image control to bytes.

My Xaml code is here.

  <ListBox Background="Transparent" Margin="-5,2,-5,10" BorderThickness="0" MaxHeight="680" Grid.Row="1" x:Name="listBoxobj" SelectionChanged="listBoxobj_SelectionChanged">
    <ListBox.ItemTemplate>
       <DataTemplate>
         <Grid Width="400" Margin="0,-10,0,0" >
           <Grid x:Name="pro_work_grid" Width="400" Height="120" Margin="0,0,0,0"
              VerticalAlignment="Bottom" Background="#31b1b0">
                <Grid.ColumnDefinitions>
                <ColumnDefinition Width="120"/>
                <ColumnDefinition />
                </Grid.ColumnDefinitions>


     //Image will give here image bytes. not the source.  
     // Not know how to bind this with list,,which contain image bytes

     <Image x:Name="work_pic" Source="{Binding image}" Width="120" Height="120"
       Stretch="Fill" VerticalAlignment="Center" Margin="0,0,0,0"
       Grid.ColumnSpan="1" HorizontalAlignment="Left"/>

      <TextBlock x:Name="pro_name1" Foreground="White" VerticalAlignment="Top" Grid.ColumnSpan="2" Margin="130,10,0,0"
       Text="{Binding  category}" FontSize="26" FontWeight="Bold">
       </TextBlock>

       <TextBlock x:Name="pro_title1" VerticalAlignment="Center" Grid.ColumnSpan="2" Margin="130,10,0,0"
        Text="{Binding title}" FontSize="20" Foreground="White">

        </TextBlock>

                        </Grid>

                    </Grid>

                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox> 

I have bind text block to directly by category,and title.. which are coming in List.

when my ListBox page loads then code work,,

  private void ReadContactList_Loaded(object sender, RoutedEventArgs e)
    {
        ReadAllContactsList dbcontacts = new ReadAllContactsList();
        DB_ContactList = dbcontacts.GetAllContacts();//Get all DB contacts 
        if (DB_ContactList.Count > 0)
        {   
        }                    
  listBoxobj.ItemsSource = DB_ContactList.OrderByDescending(i => i.Id).ToList();
    }

I'm able to get image from single image bytes. but here is the list of images display,,, so how can I get bytes and convert them into image control and show them separately in image control. Here is my Listbox items

Would you please help me?? I don't know the proper Syntax,,,Thanks in Advance

I convert image to bytes in this way.

   if (args != null)
        {
            if (args.Files.Count == 0) return;

            view.Activated -= viewActivated;
            StorageFile storageFile = args.Files[0];
            string pro_img_path = storageFile.Path;
            var stream = await storageFile.OpenAsync(Windows.Storage.FileAccessMode.Read);
            filebite = new byte[stream.Size];
            using (DataReader reader = new DataReader(stream))
            {
                await reader.LoadAsync((uint)stream.Size);
                reader.ReadBytes(filebite);
            }

Again to reconvert these bytes to bitmap image.

   using (InMemoryRandomAccessStream ms = new InMemoryRandomAccessStream())
        {

            using (DataWriter writer = new DataWriter(ms.GetOutputStreamAt(0)))
            {
                writer.WriteBytes((byte[])pro_pic_byts);
                writer.StoreAsync().GetResults();
            }


            var img1 = new BitmapImage();
            img1.SetSource(ms);// = ms;
            pro_pic.Source = img1;
        } 

回答1:

Depending on how you stored the image bytes, this may work :

public class BinaryToImageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null) return null;

        if (value is IEnumerable<byte>)
        {
            List<byte> imgData = new List<byte>((IEnumerable<byte>)value);
            BitmapImage rval = new BitmapImage();

            rval.SetSource(new System.IO.MemoryStream(imgData.ToArray()));
            return rval;
        }
        throw new NotImplementedException();
    }

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

Use this converter when binding your ImageSource to your byte[]



回答2:

just added bit code to database class and then bind to bitmapImage

 <Image  Grid.RowSpan="4" HorizontalAlignment="Right" VerticalAlignment="Top" Source="{Binding _contact.bitmapImage}" Stretch="UniformToFill" Margin="5" Width="100" Height="100" Opacity="1" />

  public byte[] Image
    {
        get
        {
            return (_imgBytes);
        }
        set
        {
            _imgBytes = value;
            CreateBitmap();
        }
    }

    private async void CreateBitmap()
    {
        var result = await dbUtils.CreateBitmap(_imgBytes);
        _bitmap = result;
    }

    [Ignore]
    public BitmapImage bitmapImage
    {
        get
        {
            return (_bitmap);
        }
    }