【发布时间】:2013-08-07 13:51:00
【问题描述】:
如何将表示为字符串的 BLOB 转换为 System.Drawing.Image 类型?
背景
我将使用 c# 从 csv 文件中导入有关用户的信息以及他们的照片。我使用的专有 SDK 要求照片是 System.Drawing.Image
以下是 csv 文件的示例。
surname firstname photo
Blogs Joe 0xFFD8FFE000104A46494600010101005F005F0000FFDB0043000D090A
photo 字段实际上是 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 或从文件中读取图像。
【问题讨论】:
-
这个 blob 字符串是 base64 编码的吗?
-
我不这么认为。格式是 SQL Server 存储其 blob 的格式。我认为捕获照片的应用程序使用 SQL Server 的本机 blob 格式。