Ошибка десериализации: параметр недействителен - PullRequest
0 голосов
/ 22 октября 2018

Мне удалось сериализовать фигуры как объект и загрузить их снова или перерисовать снова в графический блок.Теперь проблема в том, что я могу сериализовать изображение в Base64String, но не могу снова десериализовать его в Image и перерисовать в PictureBox.Любые предложения?

Я предоставил свой код для сериализации и десериализации.Я исключил ту, которая снова рисует фигуры, поскольку она не имеет отношения к вопросу.

Метод сериализации

public void Serialization()
    {
        try
        {
            XmlSerializer ser = new XmlSerializer(typeof(List<Layers>)); //Serializer
            SaveFileDialog save = new SaveFileDialog();           //Creates and Opens a SaveFileDialog
            save.Filter = "Seal Creator File (*.sealFile)|*.sealFile";     //Creates a filter fir saving the Project File
            save.DefaultExt = ".seal";
            save.AddExtension = true;

            if (save.ShowDialog() == DialogResult.OK)
            {
                //Serialization process for the Class
                FileStream file = File.Create(save.FileName);
                ser.Serialize(file, draw.layers);
                file.Close();
                MessageBox.Show("Saved"); //Saving Confirmation
            }
        }
        catch (Exception ex)
        {
            //Catching the Error
            String innerMessage = (ex.InnerException != null) ? ex.InnerException.Message : "";
            Debug.WriteLine(innerMessage);
        }
    }

Десериализация

public void Deserialize(StreamReader file)
    {
        try
        {
            List<Layers> _layers = new List<Layers>();      
            XmlSerializer ser = new XmlSerializer(typeof(List<Layers>));   
            _layers = (List<Layers>)ser.Deserialize(file);   //Here's where the program catches an error. 
        }
    }      

Так я сериализовал и десериализовал изображение в классе слоев

 [Browsable(false), EditorBrowsable(EditorBrowsableState.Never)]
    [XmlElement("ImageData")]
    public String ImageData
    {
        get
        {
            //Serialize
            using (MemoryStream ms = new MemoryStream())
            {
                // Convert Image to byte[]
                image.Save(ms, ImageFormat.Bmp);
                byte[] imageBytes = ms.ToArray();

                // Convert byte[] to Base64 String
                string base64String = Convert.ToBase64String(imageBytes);
                return base64String;
            }
        }
        set
        {
            //Deserialize
            byte[] imageBytes = Convert.FromBase64String(ImageData);
            MemoryStream ms = new MemoryStream(imageBytes, 0,
              imageBytes.Length);

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

Ошибка: параметр недействителен.

Редактировать

Класс слоя

    public enum Type
    {
       Rectangle, Square, Circle, Ellipse, Triangle, Image
    }
    public Layers.Type type { get; set; }
    public float width { get; set; }
    public float height { get; set; }
    public PointF location { get; set;}
    public int radius { get; set; }
    public int strokeThickness { get; set; }
    public Color color { get; set; }
    public Bitmap image { get; set; }

    [XmlElement("ImageData")]
    public String ImageData
    {
        get
        {
            //Serialize
            using (MemoryStream ms = new MemoryStream())
            {
                // Convert Image to byte[]
                image.Save(ms, ImageFormat.Bmp);
                byte[] imageBytes = ms.ToArray();

                // Convert byte[] to Base64 String
                string base64String = Convert.ToBase64String(imageBytes);
                return base64String;
            }
        }
        set
        {
            //Deserialize
            byte[] imageBytes = Convert.FromBase64String(ImageData);
            MemoryStream ms = new MemoryStream(imageBytes, 0,
              imageBytes.Length);

            // Convert byte[] to Image
            ms.Write(imageBytes, 0, imageBytes.Length);
            Image image = Image.FromStream(ms, true);
            this.image = (Bitmap)image;
        }
    }
    public RectangleF rect { get; set; }
    public PointF centerSerializable
    {
        get { return Shape.center; }
        set { Shape.center = value; }
    }

    public Layers(Layers.Type image, RectangleF rect, Bitmap bm)
    {
        this.type = image;
        this.rect = rect;
        this.image = bm;
    }
    public Layers (Layers.Type shape, float width, float height, int radius, int strokeThickness, Color color, PointF location)
    {
        this.type = shape;
        this.width = width;
        this.height = height;
        this.radius = radius;
        this.strokeThickness = strokeThickness;
        this.color = color;
        this.location = location;
    }
    public Layers()
    {

    }
}

}

...