首先,感谢您阅读我的问题。
我正在使用DataGridView,它使用预先存在的XML文件作为数据源:
public DataSet TableDatabase = new DataSet();
TableDatabase.ReadXml("xml_file.xml");
(DataGridView)DbTable.DataSource = TableDatabase.Tables[0];
基本xml文件是具有id,int,text的通用数据库。
我基本上想要做的是添加一个带有typeof Bitmap的新列(来自剪贴板的源代码)和将其序列化为Base64“string”。
如果我使用第一行“typeof(Bitmap)”,图像数据将显示为图像,但不知道如何序列化...
// DataColumn col = TableDatabase.Tables[0].Columns.Add("columnname", typeof(Bitmap));
DataColumn col = TableDatabase.Tables[0].Columns.Add("columnname", typeof(MyImage));
我创建了一个名为“MyImage”的类(基于Serialize a Bitmap in C#/.NET to XML):
[Serializable]
public class MyImage : IXmlSerializable
{
public Bitmap Image { get; set; }
public System.Xml.Schema.XmlSchema GetSchema()
{
return null;
}
public void ReadXml(System.Xml.XmlReader reader)
{
reader.ReadStartElement();
MemoryStream ms = null;
byte[] buffer = new byte[256];
int bytesRead;
while ((bytesRead = reader.ReadContentAsBase64(buffer, 0, buffer.Length)) > 0)
{
if (ms == null)
{
ms = new MemoryStream(bytesRead);
}
ms.Write(buffer, 0, bytesRead);
}
if (ms != null)
{
Image = (Bitmap)System.Drawing.Image.FromStream(ms,true,true);
}
reader.ReadEndElement();
}
public void WriteXml(System.Xml.XmlWriter writer)
{
using (MemoryStream ms = new MemoryStream())
{
Image.Save(ms, ImageFormat.Bmp);
byte[] bitmapData = ms.ToArray();
writer.WriteBase64(bitmapData, 0, bitmapData.Length);
}
}
}
它的工作非常好,我可以在xml中加载和写入imagedata:
<columnname>...base64 data...</columnname>
DataGridView中的数据字段不会显示为图像:(
它只显示一个字符串:“ Namespace.MyImage ”。那么如何告诉DataCell显示图像呢?
答案 0 :(得分:0)
问题在于
msdata:DataType="NAMESPACE.MyImage, APPNAME, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
转换为MyImage类,而
msdata:DataType="System.Drawing.Bitmap, APPNAME, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
会抛出看图像的方式。所以我需要知道如何定义MyImage目标是一个位图...... :(
我真的很蠢;)
[XmlIgnoreAttribute()]
public Bitmap Picture = new Bitmap(1, 1);
// Serializes the 'Picture' Bitmap to XML.
[XmlElementAttribute("Picture")]
public byte[] PictureByteArray
{
get
{
TypeConverter BitmapConverter = TypeDescriptor.GetConverter(Picture.GetType());
return (byte[])BitmapConverter.ConvertTo(Picture, typeof(byte[]));
}
set
{
Picture = new Bitmap(new MemoryStream(value));
}
}
和细胞:
DataColumn col = TableDatabase.Tables[0].Columns.Add("columnname", PictureByteArray.GetType());