Easy Way to Convert a Base64 Image to Byte Array in ASP.NET Core

Easy Way to Convert a Base64 Image to Byte Array in ASP.NET Core
Photo Credit: unsplash.com/microsoft365

In this post, we are going to write a piece of code to convert base64 image to byte array. 

I'm using a JavaScript image cropping plugin to provide the end-users the ability to crop images they upload on a Web App built on top of ASP.NET Core. The JavaScript cropping plugin is returning the image as base64 text, this is fine as in Html we can bind an image to a base64 string by setting the "src" attribute. However, in my case I need to convert this base64 image to byte array to save the binary in the SQL database then create the physical file of the cropped image.

You may ask why I need to convert the base64 image to byte array. I'm doing this for one simple reason, because the base64 image can be a large text in the Html which will increase the size of the page, as a result it can affect the page load time. Therefore, for better performance it is recommended to make use of the physical images instead of the base64 string since they can be cached in the browser. 

Step 1: Converting the Base64 String to Byte Array

First, we will convert the base64 string to byte array, note that the base64 string represents the cropped image:

byte[] bytes = Convert.FromBase64String(base64);

Step 2: Saving the Byte Array to SQL Database using ADO.NET and .NET Core

Here is the data access function I wrote to save the byte array to the SQL table. In this function, I used ADO.NET to open an SQL connection and run an SQL command, here is the code of the function:

public static bool SaveUserPhoto(byte[] bytesImage)
{
    try
    {
        string sqlQuery = "INSERT INTO UserProfile(ProfilePhoto) VALUES(@ProfilePhoto)";
        using (SqlConnection sqlConn = new SqlConnection("-your-connection-string-here-"))
        using (SqlCommand cmd = new SqlCommand(sqlQuery, sqlConn))
        {
            SqlParameter param = cmd.Parameters.Add("@ProfilePhoto", SqlDbType.VarBinary);
            param.Value = bytesImage;

            sqlConn.Open();
            cmd.ExecuteNonQuery();
            sqlConn.Close();
        }
        return true;
    }
    catch(Exception ex)
    {
        //log the error
        return false;
    }
}

Step 3: Creating the Physical Image from the Byte Array in ASP.NET Core 

Now, we need to use the byte array to create the physical file of the cropped image. To achieve this goal, we will use the class "File" in the namespace "System.IO", here is the syntax:

System.IO.File.WriteAllBytes(imagePathWithExtension, bytes);

In the preceding line of code, we used WriteAllBytes and we gave it the full path of the image where we want to save it on the disk along with its extension (that can be .jpg, .jpeg,.png,.gif, etc.) in addition to the byte array from the previous step.

Conclusion: Easy Way to Convert a Base64 Image to Byte Array in ASP.NET Core

In my actual ASP.NET Core project, I created a reusable method to convert the base64 text into byte array and save it to the disk. Here is the final code of this method:

public void CreateImageFromBase64(string base64, string imagePathWithExtension)
{
    //Convert the base64 to byte array
    byte[] bytes = Convert.FromBase64String(base64);
    //Here you can save the byte array to the SQL database. You can use your own function
    bool saved = DAL.SaveUserPhoto(bytes);
    //Create the physical image from the byte array
    System.IO.File.WriteAllBytes(imagePathWithExtension, bytes);
}

 

No Comments

Add a Comment

As it will appear on the website

Not displayed

Your website