Reputation: 718
I have a Winforms application that uploads images to SQL Server 2005 as Image
data type for SQL Server column within two methods Single
and Multiple
.
With single I send a parameter from C# to the SP as binary image.
But with multiple I need to send them as XML plain text to the DB and converting them inside the SP to image using
convert(image, @myimageFromXML, 2)
I tried many functions from other websites like
public static string ByteArrayToString(byte[] ba)
{
StringBuilder hex = new StringBuilder(ba.Length * 2);
foreach (byte b in ba)
hex.AppendFormat("{0:x2}", b);
return hex.ToString();
}
public static string ByteArrayToString(byte[] ba)
{
string hex = BitConverter.ToString(ba);
return hex.Replace("-", "");
}
public static string ByteArrayToString(byte[] Bytes)
{
char[] hexes = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
char[] Result = new char[Bytes.Length << 1];
int Offset = 0;
for (int i = 0; i != Bytes.Length; i++)
{
Result[Offset++] = hexes[Bytes[i] >> 4];
Result[Offset++] = hexes[Bytes[i] & 0x0F];
}
return new string(Result);
}
public static String ByteArrayToString(byte[] Source)
{
return "0x" + BitConverter.ToString(Source).Replace("-", "");
}
public static string ByteArrayToString(byte[] barray)
{
char[] c = new char[barray.Length * 2];
byte b;
for (int i = 0; i < barray.Length; ++i)
{
b = ((byte)(barray[i] >> 4));
c[i * 2] = (char)(b > 9 ? b + 0x37 : b + 0x30);
b = ((byte)(barray[i] & 0xF));
c[i * 2 + 1] = (char)(b > 9 ? b + 0x37 : b + 0x30);
}
return new string(c);
}
but every one of them returns data not correct and I cannot display them because it cannot be rendered as Image
My correct image within single document upload saved binary image starts with
0x49492A008C040600803FA04FF004160D0784..........
but wrong data saved with multiple upload starts with
0x310033003700380030003700380037.............
Please help me to find how to get correct binary data from C# byte[] in order to send them as XML to the SQL Server as a text
Upvotes: 3
Views: 6651
Reputation: 10357
Try to convert your image to Base64 string:
// Convert byte[] to Base64 String
string base64ImageString = Convert.ToBase64String(imageBytes);
some methods you need:
Image to Base64 String
public string ImageToBase64(Image image,
System.Drawing.Imaging.ImageFormat format)
{
using (MemoryStream ms = new MemoryStream())
{
// Convert Image to byte[]
image.Save(ms, format);
byte[] imageBytes = ms.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}
Base64 String to Image
public Image Base64ToImage(string base64String)
{
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(base64String);
MemoryStream ms = new MemoryStream(imageBytes, 0,
imageBytes.Length);
// Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length);
Image image = Image.FromStream(ms, true);
return image;
}
codes from here.
Upvotes: 2