views:

52

answers:

1

As the title mentioned, I want to encode a Image Obj into some kind of text data (compact framework not support binaryformatter, correct me if I'm wrong). So is there any way to encode a Image Obj into text data and keep it in a XML file for being able to decode from XML file to Image obj later?

UPDATE: Here is what I did following Sam's respose. Thanks Sam!

//Write to XML
byte[] Ret;
using (MemoryStream ms = new MemoryStream())
{
    myImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
    Ret = ms.ToArray();
}
StreamWriter myWrite = new StreamWriter(myPathFile);
myWrite.Write(Convert.ToBase64String(Ret));
myWrite.Flush();
myWrite.Close();

Then when I want to decode Image from Base64String to Image:

StreamReader StrR = new StreamReader(myPathFile);
BArr = Convert.FromBase64String(StrR.ReadToEnd());
using (MemoryStream ms = new MemoryStream(BArr,0,BArr.Length))
{
    ms.Write(BArr, 0, BArr.Length);
    listControl1.BGImage = new Bitmap(ms);
}
+1  A: 

Typically binary data is converted to Base64 when included in XML. Look at Convert.ToBase64String.

Sam
But in compact framework not support binaryformatter. Can you say more details?
Thyphuong
You don't need a binary formatter. Once you have the image, get the bytes, and pass the byte array to `Convert.ToBase64String`. If I get a chance I'll update the answer with a sample later.
Sam