从xml文件加载图像数据

时间:2010-02-08 19:05:31

标签: c# winforms image base64

我有以下代码从xml文件加载数据。我已经做了很长一段时间了,但是不再有那个代码了,这是行不通的。 (我可以成功地将图像数据写入文件。但加载它并转换为图像对象不起作用):

p.Image = Base64ToImage(controlTag.Attributes("Content").First().Value); // i call this on button click.

和...

public Image Base64ToImage(string base64String)
{
    // Convert Base64 String to byte[]
    byte[] imageBytes = Convert.FromBase64String(base64String);
    MemoryStream ms = new MemoryStream(imageBytes, 0,
      imageBytes.Length);

    // Convert byte[] to Image
    ms.Write(imageBytes, 0, imageBytes.Length);
    Image image = Image.FromStream(ms, true);
    return image;
}

有人可以解释为什么这不会在我的表格上显示转换后的图像吗?我根本没有任何错误...图像没有出现。

谢谢

巴尔

更新

<小时/> 以下代码用于将图像数据写入xml文件:

public string ImageToBase64(Image image, System.Drawing.Imaging.ImageFormat format)
{
    using (MemoryStream ms = new MemoryStream())
    {
        // Convert Image to byte[]
        image.Save(ms, format);
        byte[] imageBytes = ms.ToArray();

        // Convert byte[] to Base64 String
        string base64String = Convert.ToBase64String(imageBytes);
        return base64String;
    }
}

...这就是从xml文件中加载(好吧,无论如何)来处理图像并将其显示在表单上的内容:

public Image Base64ToImage(string base64String)
{
    // Convert Base64 String to byte[]
    byte[] imageBytes = Convert.FromBase64String(base64String);
    MemoryStream ms = new MemoryStream(imageBytes);
    return Image.FromStream(ms, true);
}

以下是xml文件的样子:

<?xml version="1.0" encoding="utf-8"?>
<cs>
  <PictureBox Content="Qk1mAgAAAAAAALYAAAAoAAAAFgAAABIAAAABAAgAAAAAAAAAAADEDgAAxA4AACAAAAAgAAAA/////8z///8z////AMD////MzP9mzMz/M8zM/zOZzP/AwMD/vLy8/2aZmf8zmZn/M2aZ/5CQkP9sbGz/ZmZm/zMzZv9BQUH/AAAA/8DAwAAAAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8TEw0PDw8PDRMTExMTExMTExMTExMTAAATDw8JCQkJEQ0TExAQEBAQEBMTExMTAAAODQAPCQEJCRENEAUFBQUFBRAQExMTAAAOAQ8NDwkBAAkRAwMCAgICBQULEBMTAAANDw0ADw0NAAkRAwICAgICAgUFCxATAAATDwEPDw8JAAkRAwICAgUFBQIFBRATAAATDQ8PCQEAEREDAwICAgICAgICBQsQAAATExMPDw8PEQMDAgcHBwsLCwwMBQsQAAATEw8BAA8BABEDAgcCAgICAgIFDAsQAAATEw8BDxMPAREDAwIFBQUFBQUFBQsQAAATDwEADxMPAQARAwICAgIKCgYEBAsQAAATDwEPExMQDwERAwIGBAQCBgASAAsQAAATDQ8NExMTDRENAgIGEgACAgYAABATAAATExMTExMTEAMDAgIAAAACAgYKChATAAATExMTExMTExADAwIKBgYCAgIGEBMTAAATExMTExMTExMQEAMCCgoCAhAQExMTAAATExMTExMTExMTExAQEBAQEBMTExMTAAATExMTExMTExMTExMTExMTExMTExMTAAA=" LocationX="446" LocationY="125" />
</cs>

更新

以下是我用来打开/读取/处理xml文件的代码。另请注意,所有其他控件(如标签链接标签等)都可以从文件中正确读取并成功显示在表单上。它只是没有出现的PictureBox:

private void toolStripButton1392_Click(object sender, EventArgs e)
{
    OpenFileDialog o = new OpenFileDialog();

    o.Filter =
        "T Multimedia Format (*.mf)|*.mf|" +
        "Word Document (*.docx)|*.docx|" +
        "PDF Document (*.pdf)|*.pdf|" +
        "Text FIle (*.txt)|*.txt";
    o.Title = "T 11 - Open Document";

    using (o)
    {
        if (o.ShowDialog() == DialogResult.OK)
        {
            foreach (var controlTag in XDocument.Load(o.FileName).Root.Elements())
            {
                var controlType = Type.GetType(string.Format("System.Windows.Forms.{0}, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", controlTag.Name.LocalName), false);
                if (controlType == null || !typeof(Control).IsAssignableFrom(controlType))
                {
                    continue;
                }

                var control = (Control)Activator.CreateInstance(controlType);
                control.Text = controlTag.Attributes("Content").First().Value;

                try
                {
                    control.ForeColor = Color.FromArgb(
                        int.Parse(controlTag.Attributes("A").First().Value),
                        int.Parse(controlTag.Attributes("R").First().Value),
                        int.Parse(controlTag.Attributes("G").First().Value),
                        int.Parse(controlTag.Attributes("B").First().Value));

                    Font font = FromString(controlTag.Attributes("Font").First().Value);
                    control.Font = font;
                }
                catch { continue; }

                control.BackColor = Color.Transparent;

                control.MouseDown += new MouseEventHandler(control_MouseDown);
                control.MouseMove += new MouseEventHandler(control_MouseMove);
                control.MouseUp += new MouseEventHandler(control_MouseUp);
                control.MouseClick += new MouseEventHandler(control_MouseClick);
                control.MouseDoubleClick += new MouseEventHandler(control_MouseDoubleClick);

                Type t = control.GetType();
                if (t.Name == "Label")
                {
                    Control c = control;
                    c = control;
                    Label label = (Label)control;
                    label.AutoSize = true;
                    label.Location = new Point(
                        Convert.ToInt32(controlTag.Attributes("LocationX").First().Value),
                        Convert.ToInt32(controlTag.Attributes("LocationY").First().Value));

                    Canvas.Controls.Add(label);

                    // handlers.
                    label.MouseDown += new MouseEventHandler(label_MouseDown);
                    label.MouseMove += new MouseEventHandler(label_MouseMove);
                    label.MouseUp += new MouseEventHandler(label_MouseUp);
                    label.MouseClick += new MouseEventHandler(label_MouseClick);
                    label.MouseDoubleClick += new MouseEventHandler(label_MouseDoubleClick);
                }
                else if (t.Name == "LinkLabel")
                {
                    Control c = control;

                    LinkLabel link = new LinkLabel();
                    link.AutoSize = true;
                    link.Location = new Point(
                        Convert.ToInt32(controlTag.Attributes("LocationX").First().Value),
                        Convert.ToInt32(controlTag.Attributes("LocationY").First().Value));

                    Canvas.Controls.Add(link);

                    // Add handlers.
                    link.MouseDown += new MouseEventHandler(link_MouseDown);
                    link.MouseMove += new MouseEventHandler(link_MouseMove);
                    link.MouseUp += new MouseEventHandler(link_MouseUp);
                    link.MouseClick += new MouseEventHandler(link_MouseClick);
                    link.MouseDoubleClick += new MouseEventHandler(link_MouseDoubleClick);
                }
                else if (t.Name == "PictureBox")
                {
                    Control c = control;
                    c = control;
                    PictureBox p = new PictureBox();

                    p.Image = Base64ToImage(controlTag.Attributes("Content").First().Value);
                    p.InitialImage = Base64ToImage(controlTag.Attributes("Content").First().Value);
                    p.Size = new Size(50, 50);
                    p.Location = new Point(
                        Convert.ToInt32(controlTag.Attributes("LocationX").First().Value),
                        Convert.ToInt32(controlTag.Attributes("LocationY").First().Value));

                    Canvas.Controls.Add(p);

                    // Add handlers.
                    p.MouseDown += new MouseEventHandler(p_MouseDown);
                    p.MouseMove += new MouseEventHandler(p_MouseMove);
                    p.MouseUp += new MouseEventHandler(p_MouseUp);
                    p.MouseClick += new MouseEventHandler(p_MouseClick);
                    p.MouseDoubleClick += new MouseEventHandler(p_MouseDoubleClick);
                }
            }
            this.Text = "T 11 - " + o.FileName;
        }
    }
}

1 个答案:

答案 0 :(得分:2)

您应该在MemoryStream来电后立即重置Write的位置:

ms.Position = 0;

致电Write会自动增加排名。因此,在不重置位置的情况下,流将已经结束,Image.FromStream将无法从中读取(它开始在当前位置读取)。


更新

我发现你的Write电话根本没必要。您应该直接使用MemoryStream初始化byte[],方法是将其作为构造函数传递:

byte[] imageBytes = Convert.FromBase64String(base64String);
MemoryStream ms = new MemoryStream(imageBytes);
return Image.FromStream(ms, true);

如果失败,那么您从XML读取的数据可能有问题。


更新

我的测试应用程序适用于您的图像:

using System;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using System.Xml.Linq;
class Program
{
    static void Main(string[] args)
    {
        string xml = @"<?xml version=""1.0"" encoding=""utf-8""?>
<cs>
  <PictureBox Content=""Qk1mAgAAAAAAALYAAAAoAAAAFgAAABIAAAABAAgAAAAAAAAAAADEDgAAxA4AACAAAAAgAAAA/////8z///8z////AMD////MzP9mzMz/M8zM/zOZzP/AwMD/vLy8/2aZmf8zmZn/M2aZ/5CQkP9sbGz/ZmZm/zMzZv9BQUH/AAAA/8DAwAAAAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8AAAD/AAAA/wAAAP8TEw0PDw8PDRMTExMTExMTExMTExMTAAATDw8JCQkJEQ0TExAQEBAQEBMTExMTAAAODQAPCQEJCRENEAUFBQUFBRAQExMTAAAOAQ8NDwkBAAkRAwMCAgICBQULEBMTAAANDw0ADw0NAAkRAwICAgICAgUFCxATAAATDwEPDw8JAAkRAwICAgUFBQIFBRATAAATDQ8PCQEAEREDAwICAgICAgICBQsQAAATExMPDw8PEQMDAgcHBwsLCwwMBQsQAAATEw8BAA8BABEDAgcCAgICAgIFDAsQAAATEw8BDxMPAREDAwIFBQUFBQUFBQsQAAATDwEADxMPAQARAwICAgIKCgYEBAsQAAATDwEPExMQDwERAwIGBAQCBgASAAsQAAATDQ8NExMTDRENAgIGEgACAgYAABATAAATExMTExMTEAMDAgIAAAACAgYKChATAAATExMTExMTExADAwIKBgYCAgIGEBMTAAATExMTExMTExMQEAMCCgoCAhAQExMTAAATExMTExMTExMTExAQEBAQEBMTExMTAAATExMTExMTExMTExMTExMTExMTExMTAAA="" LocationX=""446"" LocationY=""125"" />
</cs>";
        var x = XDocument.Parse(xml);
        var s = x.Descendants("PictureBox").First().Attribute("Content").Value;
        var f = new Form();
        PictureBox p = new PictureBox();
        p.Dock = DockStyle.Fill;
        f.Controls.Add(p);
        p.Image = Base64ToImage(s);
        Application.Run(f);
    }

    static Image Base64ToImage(string base64String)
    {
        byte[] imageBytes = Convert.FromBase64String(base64String);
        MemoryStream ms = new MemoryStream(imageBytes);
        return Image.FromStream(ms, true);
    }
}

检查事件处理程序,XML加载过程和其他内容。这部分代码看起来很好。