C# WPF:在单个文件中连接图像

C# WPF:在单个文件中连接图像,c#,xml,wpf,image,serialization,C#,Xml,Wpf,Image,Serialization,我叫卢卡斯,正在学习WPF/C 我想加入一个文件中的几个图像,以及一个游戏,使用多个纹理都在一个文件中,但我不知道如何做。谁能帮我想想怎么做 //Convert Image to Byte[] public byte[] getByteFromImage() { byte[] imageArray = File.ReadAllBytes(op.FileName); return imageArray; }

我叫卢卡斯,正在学习WPF/C

我想加入一个文件中的几个图像,以及一个游戏,使用多个纹理都在一个文件中,但我不知道如何做。谁能帮我想想怎么做

//Convert Image to Byte[]

    public byte[] getByteFromImage()
        {
            byte[] imageArray = File.ReadAllBytes(op.FileName);
            return imageArray;
        }

//Convert Byte[] to Image

        public void getImageFromByte()
        {
            FileStream f = new FileStream("escudos.bcf", FileMode.Open);
            BinaryReader b = new BinaryReader(f);

            Int64 c = f.Length+1;
            MemoryStream ms = new MemoryStream(b.ReadBytes(int.Parse(c.ToString())));
            Image image = new Image();
            image.Source = BitmapFrame.Create(ms, BitmapCreateOptions.None,
                                      BitmapCacheOption.OnLoad);

            imgPatch2.Source = image.Source;
            f.Dispose();
        }

//Create Binary File

        public void save(byte[] img)
        {
            FileStream f;

            if (!File.Exists("escudos.bcf"))
            {
                f = new FileStream("escudos.bcf", FileMode.Create);
            }

            else
            {
                f = new FileStream("escudos.bcf", FileMode.Append);
            }

            BinaryWriter b = new BinaryWriter(f);
            b.Write(img);
            b.Close();
            f.Dispose();
        }
我认为这样做,创建一个文件并将其存储在二进制图像中。 直到我得到那个部分,但由于这个文件将有多个二进制图像,我不知道如何只选择一个二进制图像

public void xmlCreate(string name, Int64 ini, Int64 fin)
        {
            if (!File.Exists("Escudos.xml")) 
            {
                XmlTextWriter w = new XmlTextWriter("Escudos.xml", System.Text.Encoding.UTF8);
                w.Formatting = Formatting.Indented;

                w.WriteStartDocument();

                w.WriteStartElement("Time");
                w.WriteStartElement(name);
                w.WriteElementString("Inicio", ini.ToString());
                w.WriteElementString("Fim", fin.ToString());
                w.WriteEndElement();
                w.WriteEndDocument();

                w.Close();
            }

            else
            {


                XDocument doc = XDocument.Load("Escudos.xml");
                doc.Root.Add(new XElement(name));
                doc.Root.Element(name).Add(new XElement("Inicio", ini.ToString()));
                doc.Root.Element(name).Add(new XElement("Fim", fin.ToString()));
                doc.Save("Escudos.xml");


            }
        }
现在我创建了一个xml文件来存储字节的开始和结束。我只能在创建新的xml文件时添加,而不能创建xml并添加新字节。当我去加载xml文件时,会给出一条错误消息

“System.Xml.dll中发生“System.Xml.XmlException”类型的未处理异常 其他信息:“>”是意外标记。预期标记为“=”。第3行,位置15。“


更新

当我读取字节以形成图像时,总是以相同的方式,即使我添加了不同的图像。我将在下面添加代码

//Add Image

private void btAddImage_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog op = new OpenFileDialog();
            op.Title = "Selecione a Imagem";
            op.Filter = "All supported graphics|*.jpg;*.jpeg;*.png|" +
                "JPEG (*.jpg;*.jpeg)|*.jpg;*.jpeg|" +
                "Portable Network Graphic (*.png)|*.png";

            if (op.ShowDialog() == true)
            {
                imgPatch.Source = new BitmapImage(new Uri(op.FileName));
                txtName.Focus();
            }
        }


//Convert Image

 private void btConvertImage_Click(object sender, RoutedEventArgs e)
        {
            if (String.IsNullOrEmpty(txtName.Text))
            {
                txtName.Focus();
                MessageBox.Show("Preencha o Nome", "Error");
            }

            else
            {
                save(ConvertFileToByteArray(op.FileName), txtName.Text);
            }
        }

//Image to Byte Array

private static byte[] ConvertFileToByteArray(String FilePath)
        {
            return File.ReadAllBytes(FilePath);
        }


//Save Binary File and XML File

public void save(byte[] img, string nome)
        {
            FileStream f;
            long ini, fin = img.Length; 

            if (!File.Exists("Escudos.bcf"))
            {
                f = new FileStream("Escudos.bcf", FileMode.Create);
                ini = 0;
            }

            else
            {
                f = new FileStream("Escudos.bcf", FileMode.Append);
                ini = f.Length + 1;
                bin = new TestBinarySegment();

            }

            bin.LoadAddSave("Escudos.xml", "Brasileiro", nome, ini, fin);



            BinaryWriter b = new BinaryWriter(f);
            b.Write(img);
            b.Close();
            f.Dispose();



        }


//Load Image from Byte
private void btLoad_Click(object sender, RoutedEventArgs e)
        {
            getImageFromByte();
        }


//Byte to Image
public void getImageFromByte(int start, int length)
        {
            using (FileStream fs = new FileStream("Escudos.bcf", FileMode.Open))
            {
                byte[] iba = new byte[fs.Length+1];
                fs.Read(iba, start, length);
                Image image = new Image();
                image.Source = BitmapFrame.Create(fs, BitmapCreateOptions.None,
                                          BitmapCacheOption.OnLoad);

                imgPatch2.Source = image.Source;
            }
        }

感谢您提供了一个二进制文件,其中的内容是段,每个段都包含创建图像所需的二进制信息。您需要存储每个段的起始索引和长度,以便检索它。一种方法是使用xml文件

首先,为段创建一个容器类。看起来像这样

public class BinarySegment
{
    private const string FileName = "SegmentData.xml";
    private static XmlSerializer serializer = new XmlSerializer(typeof(List<BinarySegment>));
    public string SegmentName { get; set; }
    public long SegmentStartIndex { get; set; }
    public long SegmentLength { get; set; }
    public static List<BinarySegment> LoadFromFile()
    {
        if (!File.Exists(FileName))
        {
            throw new Exception("File must be created first");
        }
        try
        {
            using (StreamReader sr = new StreamReader(FileName))
            {
                return serializer.Deserialize(sr) as List<BinarySegment>;
            }
        }
        catch
        {
            throw new Exception("File as become corrupted");
        }
    }
    public static void Save(List<BinarySegment> list)
    {
        try
        {
            using (StreamWriter sw = new StreamWriter(FileName))
            {
                serializer.Serialize(sw, list);
            }
        }
        catch
        {
            throw;
        }
    }
}
public class TestBinarySegment
{
    public TestBinarySegment()
    {
        List<BinarySegment> myBinarySegments = new List<BinarySegment>();
        myBinarySegments.Add(new BinarySegment{SegmentName = "Segment1", SegmentStartIndex = 0, SegmentLength = 1111});
        myBinarySegments.Add(new BinarySegment { SegmentName = "Segment2", SegmentStartIndex = 1111, SegmentLength = 1111 });
        myBinarySegments.Add(new BinarySegment { SegmentName = "Segment3", SegmentStartIndex = 2222, SegmentLength = 1111 });
        BinarySegment.Save(myBinarySegments);
    }
    public void LoadAddSave()
    {
        List<BinarySegment> myBinarySegments = BinarySegment.LoadFromFile();
        myBinarySegments.Add(new BinarySegment { SegmentName = "Segment4", SegmentStartIndex = 333330, SegmentLength = 1111 });
        BinarySegment.Save(myBinarySegments);
    }
}
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfBinarySegment xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <BinarySegment>
    <SegmentName>Segment1</SegmentName>
    <SegmentStartIndex>0</SegmentStartIndex>
    <SegmentLength>1111</SegmentLength>
  </BinarySegment>
  <BinarySegment>
    <SegmentName>Segment2</SegmentName>
    <SegmentStartIndex>1111</SegmentStartIndex>
    <SegmentLength>1111</SegmentLength>
  </BinarySegment>
  <BinarySegment>
    <SegmentName>Segment3</SegmentName>
    <SegmentStartIndex>2222</SegmentStartIndex>
    <SegmentLength>1111</SegmentLength>
  </BinarySegment>
  <BinarySegment>
    <SegmentName>Segment4</SegmentName>
    <SegmentStartIndex>333330</SegmentStartIndex>
    <SegmentLength>1111</SegmentLength>
  </BinarySegment>
</ArrayOfBinarySegment>
        TestBinarySegment test = new TestBinarySegment();
        test.LoadAddSave();

这展示了如何使用xml序列化来创建文件并向其中添加新段。您需要测试这个概念,然后将其集成到您的项目中。

我看到了问题,您需要一个XML数据文件来存储每个图像的Rect结构。因此,我需要创建一个XML数据文件来存储二进制代码?不,您需要存储二进制文件中每个图像的x,y位置。据我所知,我使用的xml文件知道一个图像从字节0到字节100,另一个图像从字节101到200,是的,没错。您存储位置并使用它们提取文件非常好,我理解并可以应用códio,谢谢!但我想知道是否可以在文档“ArrayOfBinarySegment”元素的开头使用mustar。“二进制段重命名”这个词可以改变类,但是什么数组呢?我已经知道了,谢谢,现在我将尝试实现它的一部分来分离生成的数据的字节file@LucasGuitar,不用谢。请阅读“如果您仍然需要帮助,请告诉我”OK,我已标记为“答案”,如果我有任何问题,请发表意见,谢谢:)@LucasGuitar我编辑了您问题上的标记,以包括xml和序列化。它们更合适。