Hi
This seems to be quite a tricky one.
I am uploading images into a database using C# 4.
I serialize them, then convert them to byte[] so that they can be loaded into a "Image" type field.
This works great.
If I convert back from byte[] to string and save the image, it saves perfectly and there are no issues.
Now the catch is, I need to show these images in a silverlight application, s they get used in another application (which happens to be a silverlight application).
Now Silverlight doesn't have a bitmap class, only a Bitmap image.
When I try and deserialize I get the following error:
Type 'System.Windows.Media.ImageSource' cannot be serialized. Consider marking it with the DataContractAttribute attribute, and marking all of its members you want serialized with the DataMemberAttribute attribute. Alternatively, you can ensure that the type is public and has a parameterless constructor - all public members of the type will then be serialized, and no attributes will be required.<br />
My Code to Serialize:
byte[] newByte = new byte[0];
string fileName = System.IO.Path.GetFileName(s);
Guid CustomPinID = new Guid(Session["Upload"].ToString());
Bitmap myImage = new Bitmap(s);
oDataService.InsertCustomPinImage(CustomPinID, oDataService.GetMyBytes(SerializeMe(myImage)), 0.00, 0.00, fileName);
public string SerializeMe(object obj)
{
using (MemoryStream memoryStream = new MemoryStream())
{
System.Runtime.Serialization.DataContractSerializer serializer = new System.Runtime.Serialization.DataContractSerializer(obj.GetType());
serializer.WriteObject(memoryStream, obj);
return Encoding.UTF8.GetString(memoryStream.ToArray());
}
}
public byte[] GetMyBytes(string text)
{
return ASCIIEncoding.UTF8.GetBytes(text);
}
My Code is to Deserialize below:
BitmapImage DisplayImage = new BitmapImage();
DisplayImage = (BitmapImage)(cSerialization.DeserializeMe(cSerialization.GetMyString(oPinImage.imagePath), typeof(BitmapImage)));
public class Serialization
{
public string GetMyString(byte[] oArray)
{
return Encoding.UTF8.GetString(oArray, 0, oArray.Length);
}
public object DeserializeMe(string xml, Type toType)
{
using (MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
{
System.Runtime.Serialization.DataContractSerializer serializer = new System.Runtime.Serialization.DataContractSerializer(toType);
return serializer.ReadObject(memoryStream);
}
}
}