Blob_Datagrid - lucyberryhub/WPF.Tutorial GitHub Wiki

Reading JSON Blob Data and Displaying Images in a DataGrid

This tutorial will explain in detail how to read image data stored as a JSON blob, convert it into an image, and display it in a WPF DataGrid.

1. Understanding the Concept

Before writing code, let's understand what we are trying to do.

πŸ“Œ What is a JSON Blob?

  • JSON (JavaScript Object Notation) is a format for storing data.
  • A blob (Binary Large Object) is raw binary data, like an image, stored in base64 format inside JSON.
  • Instead of storing an image file on a computer, we can store the image as text (base64) in a JSON file.

πŸ“Œ How will we display the image in a DataGrid?

  1. Read JSON data and extract the base64 image data.
  2. Convert base64 into an actual image.
  3. Display the image in a WPF DataGrid.

2. Sample JSON File with Blob Data

Let's assume we have a JSON file (data.json) that contains image data like this:

[
    {
        "Id": 1,
        "Name": "Apple",
        "ImageData": "/9j/4AAQSkZJRgABAQAAAQABAAD..."
    },
    {
        "Id": 2,
        "Name": "Banana",
        "ImageData": "/9j/4AAQSkZJRgABAQAAAQABAAD..."
    }
]

Here:

  • Id β†’ A unique number for each item.
  • Name β†’ The name of the item.
  • ImageData β†’ The base64 string of an image.

3. Creating the WPF Application

Step 1: Create a Model Class

A model is a class that represents the structure of our data.

public class FruitModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string ImageData { get; set; }

    public ImageSource Image
    {
        get
        {
            return ConvertBase64ToImage(ImageData);
        }
    }

    private ImageSource ConvertBase64ToImage(string base64String)
    {
        if (string.IsNullOrEmpty(base64String))
            return null;

        byte[] binaryData = Convert.FromBase64String(base64String);
        using (MemoryStream stream = new MemoryStream(binaryData))
        {
            BitmapImage image = new BitmapImage();
            image.BeginInit();
            image.StreamSource = stream;
            image.CacheOption = BitmapCacheOption.OnLoad;
            image.EndInit();
            return image;
        }
    }
}

Explanation:
βœ” Id & Name β†’ Represent the fruit’s details.
βœ” ImageData β†’ Holds the base64 image string.
βœ” Image Property β†’ Automatically converts the base64 string into an actual image.


Step 2: Load JSON Data

We need a function to read the JSON file and convert it into objects.

using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Newtonsoft.Json;

public class DataService
{
    private const string JsonFilePath = "data.json";

    public async Task<List<FruitModel>> LoadDataAsync()
    {
        if (!File.Exists(JsonFilePath))
            return new List<FruitModel>();

        string jsonData = await File.ReadAllTextAsync(JsonFilePath);
        return JsonConvert.DeserializeObject<List<FruitModel>>(jsonData);
    }
}

Explanation:
βœ” Checks if the JSON file exists.
βœ” Reads the JSON file asynchronously.
βœ” Converts JSON text into a list of FruitModel objects.


Step 3: Display Data in a WPF DataGrid

Modify your MainWindow.xaml file:

<Window x:Class="ImageDisplay.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="JSON Image Display"
        Height="400" Width="600">
    
    <Grid>
        <DataGrid x:Name="dataGrid"
                  AutoGenerateColumns="False"
                  ItemsSource="{Binding Fruits}"
                  HorizontalAlignment="Stretch"
                  VerticalAlignment="Stretch">
            
            <DataGrid.Columns>
                <DataGridTextColumn Header="ID" Binding="{Binding Id}" Width="50"/>
                <DataGridTextColumn Header="Name" Binding="{Binding Name}" Width="150"/>
                <DataGridTemplateColumn Header="Image" Width="150">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Image Source="{Binding Image}" Width="50" Height="50"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</Window>

Explanation:
βœ” DataGrid displays Id, Name, and Image.
βœ” DataGridTextColumn is used for text fields (Id & Name).
βœ” DataGridTemplateColumn is used to display images.


Step 4: Load Data into DataGrid

Modify MainWindow.xaml.cs to load the data when the window opens.

using System.Collections.ObjectModel;
using System.Windows;

public partial class MainWindow : Window
{
    public ObservableCollection<FruitModel> Fruits { get; set; } = new ObservableCollection<FruitModel>();

    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
        LoadData();
    }

    private async void LoadData()
    {
        DataService service = new DataService();
        var data = await service.LoadDataAsync();
        foreach (var item in data)
        {
            Fruits.Add(item);
        }
    }
}

Explanation:
βœ” ObservableCollection<FruitModel> updates the UI automatically when data changes.
βœ” LoadData() reads JSON data and updates the DataGrid.


4. Running the Application

When you run the application, the DataGrid will display:

ID Name Image
1 Apple πŸ–ΌοΈ (Apple Image)
2 Banana πŸ–ΌοΈ (Banana Image)

βœ” Images are automatically converted from base64 and shown in the table! πŸŽ‰


5. Summary

1️⃣ JSON stores image data as base64.
2️⃣ Model class converts base64 into images.
3️⃣ Service class reads JSON and converts it into objects.
4️⃣ WPF DataGrid binds data and displays images.

This method is used in real-world applications for displaying user avatars, product images, and scanned documents. πŸš€

⚠️ **GitHub.com Fallback** ⚠️