Convert Image to Base64 String in Blazor C# | CodeLSC

 


Introduction:

In this blog post, we will explore how to convert an image file to a Base64 string in a Blazor application using C#. We'll provide you with a ready-to-use code snippet that you can easily implement and test in your own project.

 

Code Explanation:

The provided code demonstrates a simple Blazor component that allows users to upload an image file and converts it to a Base64 string. Let's go through the important parts of the code:

 

1. File Upload:

The component contains an `<InputFile>` element that enables users to select an image file. When a file is selected, the `HandleFileSelection` method is triggered.

<div class="container">

    <h3>Convert File to Base64 - CodeLSC</h3>

    <label for="images" class="drop-container">

        <span class="drop-title">Drop files here</span>

        or

        <InputFile id="images" class="file-input" OnChange="HandleFileSelection"></InputFile>

    </label>

</div>

 

2. HandleFileSelection:

The `HandleFileSelection` method retrieves the selected file from the event arguments. It then reads the file content and converts it to a byte array. Finally, it converts the byte array to a Base64 string and assigns it to the `base64String` variable.

@code {

    private string base64String = string.Empty;

 

    private async Task HandleFileSelection(InputFileChangeEventArgs e)

    {

        var file = e.GetMultipleFiles().FirstOrDefault();

        if (file != null)

        {

            var buffer = new byte[file.Size];

            using (var stream = file.OpenReadStream())

            {

                await stream.ReadAsync(buffer, 0, buffer.Length);

            }

            base64String = Convert.ToBase64String(buffer);

        }

    }

}

 

3. Display Base64 String:

If a Base64 string is available (i.e., the `base64String` variable is not empty), the component displays it in a `<div>` element. Additionally, a "Copy" button is provided to copy the Base64 string to the clipboard.

<div class="container">

    @if (!string.IsNullOrEmpty(base64String))

    {

        <div class="base64-string">

            <button class="copy-button" @onclick="CopyBase64String">Copy</button>

            <div style="padding: 20px;">

                @base64String

            </div>

        </div>

    }

</div>

 

4. CopyBase64String:

The `CopyBase64String` method uses JavaScript interop to invoke the `navigator.clipboard.writeText` function, which copies the Base64 string to the clipboard. This feature requires the `IJSRuntime` service, which is injected into the component.

@code {

    private string base64String = string.Empty;

 

    private async Task CopyBase64String()

    {

        await JSRuntime.InvokeAsync<object>("navigator.clipboard.writeText", new object[] { base64String });

    }

}

 

Full Code:

@using Microsoft.AspNetCore.Components.Forms

@using System.IO

@inject IJSRuntime JSRuntime

 

<div class="container">

    <h3>Convert File to Base64 - CodeLSC</h3>

    <label for="images" class="drop-container">

        <span class="drop-title">Drop files here</span>

        or

        <InputFile id="images" class="file-input" OnChange="HandleFileSelection"></InputFile>

    </label>

 

    @if (!string.IsNullOrEmpty(base64String))

    {

        <div class="base64-string">

            <button class="copy-button" @onclick="CopyBase64String">Copy</button>

            <div style="padding: 20px;">

                @base64String

            </div>

        </div>

    }

</div>

 

@code {

    private string base64String = string.Empty;

 

    private async Task HandleFileSelection(InputFileChangeEventArgs e)

    {

        var file = e.GetMultipleFiles().FirstOrDefault();

        if (file != null)

        {

            var buffer = new byte[file.Size];

            using (var stream = file.OpenReadStream())

            {

                await stream.ReadAsync(buffer, 0, buffer.Length);

            }

            base64String = Convert.ToBase64String(buffer);

        }

    }

 

    private async Task CopyBase64String()

    {

        await JSRuntime.InvokeAsync<object>("navigator.clipboard.writeText", new object[] { base64String });

    }

}

 

Conclusion:

By using the provided code snippet, you can easily implement a feature in your Blazor application that allows users to convert an image file to a Base64 string. This can be useful in various scenarios, such as uploading images to servers or displaying images directly in your application.

 

Remember to keep the original code intact, as you have already tested it and confirmed its functionality. Feel free to modify the blog content as needed and adapt it to your writing style or any additional explanations you would like to provide. Happy coding!


#Blazor #CSharp #ImageToBase64 #WebDevelopment #ProgrammingTutorial

Comments