Home > OS >  Converting an SQL image to Base64 in C#
Converting an SQL image to Base64 in C#

Time:09-24

I have a database storing Binary JPEG Images with two different file signatures (FFD8FFE0 and FFD8DDE1) and I would like to convert them into Base64 so I can use them in another application (Power BI). The data is stored as an IMAGE field type, however I only receive the data in a CSV file and import into my tool as a string and work with it from there.

For the file signature FFD8FFE0, I have no problem converting using the below code (from another Stack post - thank you):

    public static string ToBase64(String sBinary)
    {
        int noChars = sBinary.Length;

        byte[] bytes = new byte[noChars / 2];

        for (int i = 0; i < noChars; i  = 2)
        {
            bytes[i / 2] = Convert.ToByte(sBinary.Substring(i, 2), 16);
        }
        return Convert.ToBase64String(bytes);
    }

However, the file signature FFD8FFE1 is not converting and displaying properly to an image. It gives me an output, but does not display properly.

Any advice? Is this because of the different file signature OR because of the size of the string (they are noticeably larger).

EDIT: Thank you everyone who assisted. As mentioned in the comments, the real issue was the data I was trying to convert - it was being truncated in the CSV. So for anything who ever comes across this post, pull directly from SQL and not a text file as there is a good chance the data will be truncated.

CodePudding user response:

If you are looking to convert to a base64 jpg url:

public static string ToBase64PNGUrl (byte[] bytes) =>
    $"data:image/jpg;base64,{Convert.ToBase64String(bytes)}";

CodePudding user response:

You are mapping the results from the database incorrectly, this field should be byte[], not string.

I assume you are receiving a hexadecimal representation of the bytes, which you could convert to bytes then convert to base64 as you attempted (Convert.ToBase64String(bytes)).

Try using EF-code first to read from table and define the image property as byte[].

  •  Tags:  
  • c#
  • Related