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;
}
CodePudding user response:
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);
Let me know if this helped or was the solution you were looking for.
CodePudding user response:
The question was related to stored HEX values in the DB not matching the expected values. Documentation said Base64, but test showed Hex. The issue was purely missing prefix and formating.
Continuing on @data03`s solution:
byte[] imageBytes = GetImage(imgsrc);
string imageData = BitConverter.ToString(imageBytes).Replace("-", "").ToLower();
and finally the sql statment adding the prefix:
var sql = $"insert into ProductImages(ProductId, ColorId, Picture) values({prodid}, {colorId}, 0x{imageData})";