CyberRat CyberRat - 8 months ago 52
C# Question

Windows Forms Aplication-converting string to canvas drawing

The following is all in c#:
I'm using various graphic methods to draw on a canvas(LevelPanel), which I then save to an XML file. I do so by converting it to a string:

private void Save_Click(object sender, EventArgs e)
string filename = FileNameBox.Text;

Bitmap bmp = new Bitmap(LevelPanel.Width, LevelPanel.Height);
Graphics g = Graphics.FromImage(bmp);
Rectangle rect = LevelPanel.RectangleToScreen(LevelPanel.ClientRectangle);
g.CopyFromScreen(rect.Location, Point.Empty, LevelPanel.Size);
string picString = "";

using (MemoryStream m = new MemoryStream())
bmp.Save(m, ImageFormat.Png);
picString = Convert.ToBase64String(m.ToArray());
File.WriteAllText(@filename, picString);


Is there any way I could load the file (take the string and convert it back to the image). I looked around, but couldn't find anything on this. Any help is gratefully recived. If it is impossible, could anybody suggest alternative methods of saving/loading the image as an xml file.


If you're just saving the XML with File.WriteAllText("somefile.xml", picString);

Read the xml like this

string base64String = File.ReadAllText("somefile.xml");

After reading the XML file you can convert it back to an image by calling this method

public static Image ImageFromBase64String(string base64String)
    byte[] imageBytes = Convert.FromBase64String(base64String);

    using (MemoryStream ms = new MemoryStream(imageBytes))
       return Image.FromStream(ms);