问题
I've run into an annoying problem with some code I use to serialize an image's byte array to XML and back again, when reading the bytes back after deserialization there are constant changes in certain bytes.
My code is image format agnostic but for the case in point i'm using a PNG image (i've tested on several png files).
The serialize code:
var serializer = new XmlSerializer(instance.GetType());
using (var sw = new StringWriter())
{
serializer.Serialize(sw, instance);
return sw.ToString();
}
The deserialize code:
public T Deserialize<T>(string xml)
where T : class, new()
{
var serializer = new XmlSerializer(typeof (T));
using (var stringReader = new StringReader(xml))
{
return (T) serializer.Deserialize(stringReader);
}
}
Xml mapping attribute:
[System.Xml.Serialization.XmlElementAttribute(DataType="base64Binary")]
public byte[] Image
{
get
{
return this.imageField;
}
set
{
this.imageField = value;
}
}
differences found:
embedded bytes belong to an embedded image used for a unit test, image from contract is the byte array image from the deserialized contract.
embeddedBytes[73]=194, imageFromContract[73] = 192
embeddedBytes[77]=194, imageFromContract[77] = 192
embeddedBytes[79]=21, imageFromContract[79] = 106
embeddedBytes[80]=40, imageFromContract[80] = 214
embeddedBytes[81]=74, imageFromContract[81] = 137
embeddedBytes[82]=128, imageFromContract[82] = 9
this is how i get the image bytes (GetImage() simply returns the Image from the embedded resource)
public static byte[] GetImageBytes()
{
var img = GetImage();
var embeddedImageMemStream = new MemoryStream();
img.Save(embeddedImageMemStream, img.RawFormat);
return embeddedImageMemStream.ToArray();
}
If anyone can shed some light on the matter it would be greatly appreciated.
Thanks in advance
Edit: included one of the tested images,

来源:https://stackoverflow.com/questions/8960947/weird-behavior-during-image-byte-array-serialization