Search code examples
c#imagebase64hex

Convert image to Hex from URL in C# Console program


I am trying to convert images from URL into a SQL Server database on an existing system (Image table recovery), not knowing exactly the encoding.

From a working table, data in the Picture column starts with 0x89504E470D ....

It is supposed to be Base64. Testing this encoding here https://base64.guru/converter/encode/hex reveals that the encoding is HEX. Converting it to Base64 gives an image back, as it supposed to.

When I try to encode an image into base64, the data in the picture column starts with 0X2f. Testing the output at the same decoder webpage as before still generate Base64, but the base64 returns an invalid image (can't be opened, and the program that reads the database just crashes).

The question is: how can I create a function that fetch an image from URL and convert it into Hex/Base64 code that starts with 0x89504E470D?

public static byte[] GetImage(string url)
{
        Stream stream = null;
        byte[] buf;

        try
        {
            WebProxy myProxy = new WebProxy();
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);

            HttpWebResponse response = (HttpWebResponse)req.GetResponse();
            stream = response.GetResponseStream();
            //var str = new SoapHexBinary(File.ReadAllBytes(stream)).ToString();
            
            using (BinaryReader br = new BinaryReader(stream))
            {
                int len = (int)(response.ContentLength);
                buf = br.ReadBytes(len);
                br.Close();
            }

            stream.Close();
            response.Close();
        }
        catch (Exception exp)
        {
            buf = null;
        }

        return (buf);
}

public static string GetBase64String(string PathToFile)
{
        var str = new SoapHexBinary(File.ReadAllBytes(PathToFile)).ToString();
        return str;
}    

Solution

  • I have tested your code and modified some stuff and this turned out working for me. I was able to convert the hex to base64 and then the base64 to image also worked on the website you provided. Here is the code I used:

    The updated version of GetBase64String method:

    public static string GetHexString(byte[] imageBytes)
    {
        return BitConverter.ToString(imageBytes).Replace("-", string.Empty);
    }
    

    The updated version of GetBase64String method:

    public static string GetBase64String(byte[] imageBytes)
    {
        return Convert.ToBase64String(imageBytes);
    }
    

    And this is how I called them:

    byte[] imageBytes = GetImage(url);
    string hex = GetHexString(imageBytes);
    string base64 = GetBase64String(imageBytes);