简体   繁体   English

使用SQL数据库中的“图像”列的C#数据集GetXml方法

[英]C# Dataset GetXml method using Image column in SQL Database

I have a data table in SQL 2008 R2 which is used to store images. 我在SQL 2008 R2中有一个数据表,用于存储图像。 There is one column for uploaded image data whose SQL data type is "Image" 对于SQL数据类型为“图像”的上载图像数据,只有一列

On the asp.NET layer I pull data into a dataset and then call GetXml() to get an XML string and then put the xml into a text file for import/export. 在asp.NET层上,我将数据提取到数据集中,然后调用GetXml()以获取XML字符串,然后将xml放入文本文件中以进行导入/导出。

The image data is serialized into text but I can't figure out how it's encoded. 图像数据被序列化为文本,但是我不知道它是如何编码的。

Original image data in the table: 0x89504E.... Image data in my XML string: iVBORw0KGgo... 表中的原始图像数据:0x89504E .... XML字符串中的图像数据:iVBORw0KGgo ...

I need to recover the String representation of the original 0x89504E.... and I assume that's HEX. 我需要恢复原始0x89504E的String表示形式。...,我认为这是十六进制。 What encoding is the iVBORw0KGgo... ? iVBORw0KGgo ...是什么编码? I can't find the info anywhere. 我在任何地方都找不到信息。

The encoding is base64 . 编码为base64

The following code takes some binary data, puts it in a DataSet, runs GetXml(), and decodes the string in the XML as base64: 以下代码获取一些二进制数据,将其放入DataSet中,运行GetXml(),并将XML中的字符串解码为base64:

// Create a DataSet, DataTable, and define a binary column
DataSet dataSet = new DataSet("dataSet");
DataTable table = dataSet.Tables.Add("Items");
table.Columns.Add("image", typeof(byte[]));

/// Add one row of binary data (creating fake binary data from a string)
byte[] testData = new ASCIIEncoding().GetBytes("StackOverflow");
Console.WriteLine("Test data: " + new ASCIIEncoding().GetString(testData));
DataRow row = table.NewRow();
row["image"] = testData;
table.Rows.Add(row);

// Convert to XML and fetch the XML representation of the binary data
string xml = dataSet.GetXml();
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string xmlImageData = doc.SelectSingleNode("//image").InnerText;
Console.WriteLine("XML data: " + xmlImageData);

// base64decode the XML data and print its value
byte[] decoded = Convert.FromBase64String(xmlImageData);
Console.WriteLine("Decoded data: " + new ASCIIEncoding().GetString(decoded));

Output: 输出:

Test data: StackOverflow
XML data: U3RhY2tPdmVyZmxvdw==
Decoded data: StackOverflow

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM