如何将SQL Server BLOB字符串转换为System.Drawing.Image?

如何将表示为字符串的BLOB转换为System.Drawing.Image类型?

背景

我将使用c#从csv文件导入有关用户的信息及其照片。 我使用的专有SDK要求照片是System.Drawing.Image

下面是csv文件的示例。

surname firstname photo Blogs Joe 0xFFD8FFE000104A46494600010101005F005F0000FFDB0043000D090A 

照片字段实际上是5k字符长,并且是在sql server db中直接导出BLOB字段值。 我们刚刚从数据库字段中取出原始值并将其导出到csv文件。

下面的代码演示了我有多远。 cvsuser变量表示csv文件的一行。

 // We need to convert the photo from a string to a byte array string strPhoto = null; strPhoto = csvuser.photo; // The string that represents the BLOB byte[] bytes = new byte[strPhoto.Length * sizeof(char)]; System.Buffer.BlockCopy(strPhoto.ToCharArray(), 0, bytes, 0, bytes.Length); // Then we create a memory stream that holds the image MemoryStream photostream = new MemoryStream( bytes ); // Then we can create a System.Drawing.Image by using the Memory stream var photo = Image.FromStream(photostream); 

但是, Image.FromStream()行抛出System.ArgumentException,并显示消息“参数无效”。

如何将表示为字符串的BLOB转换为System.Drawing.Image类型?

我之前看到的例子是,例如,直接从数据库中获取blob或从文件中读取图像。

问题是hex编码的字符串到字节数组之间的转换不是属性。

您列出的代码会将blob中的每个字符视为一个字节,因此“F”将被视为0x46(大写字母F的ascii代码)。 你想要做的是将每2个字符解码为单个字节 – 即F0 = 240等。

它假定字符串是偶数个字符。 您还需要去除’0x’前缀,因为这只是一个指示符,表示后面是数据的hex表示。

所以不是这样的:

 strPhoto = csvuser.photo; // The string that represents the BLOB byte[] bytes = new byte[strPhoto.Length * sizeof(char)]; System.Buffer.BlockCopy(strPhoto.ToCharArray(), 0, bytes, 0, bytes.Length); 

做这样的事情(改编自此处给出的答案):

  strPhoto = csvuser.photo; // The string that represents the BLOB //remove first 2 chars (the '0x') strPhoto = strPhoto.Remove(0, 2); //convert hex-string to bytes: int NumberChars = strPhoto.Length/2; byte[] bytes = new byte[NumberChars]; using (StringReader sr = new StringReader(strPhoto)){ for (int i = 0; i < NumberChars; i++) bytes[i] = Convert.ToByte(new string(new char[2]{(char)sr.Read(), (char)sr.Read()}), 16); } // Then we create a memory stream that holds the image MemoryStream photostream = new MemoryStream( bytes ); // Then we can create a System.Drawing.Image by using the Memory stream var photo = Image.FromStream(photostream); 

这样做是为了将您的string转换为byte[]

 System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); Byte[] bytes = encoding.GetBytes(strPhoto);