首页 > 解决方案 > 在 C# 中将 .mjpeg 文件的十六进制数据保存为 .mjpeg 格式的文件

问题描述

我有一个填充了 .mjpeg 格式文件的十六进制数据(如“FFD8FE00..”)的文本文件。我必须用转换器玩它。因此,我正在尝试使用以下几行将数据写入 .mjpeg 文件:

string myData  = File.ReadAllText("hexData.txt");
string newData;
int remainder  = myData.Length%500;
byte[] data_toWrite=newByte[250];

for(int i=0;i<myData.Length-remainder; i+=500)
{
    newData     = myData.Substring(i,500);
    data_toWrite = StringToByteArray(newData);
    File.WriteAllBytes("video.mjpeg",data_toWrite);
}

newData     = myData.Substring(myData.Length-remainder,remainder);
data_toWrite = StringToByteArray(newData);
File.WriteAllBytes("video.mjpeg",data_toWrite);

public static byte[] StringToByteArray(String hex)
{
  int NumberChars = hex.Length;
  byte[] bytes = new byte[NumberChars / 2];
  for (int i = 0; i < NumberChars; i += 2)
  bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
  return bytes;
}

但我无法让它发挥作用。我不知道我错在哪里。我试图将 newData 转换为 ascii 然后字节数组,但它也失败了。

任何想法,非常感谢!

凯恩

标签: c#arrayscodecmjpeg

解决方案


这个

File.WriteAllBytes("video.mjpeg",data_toWrite);

每次都覆盖文件,而不是追加。

我确信可以编写更好的代码,但这应该足够了:

string input = "test.hex";
string output = "output.bin";

using (var sr = new StreamReader(input))
using (var fs = File.Create(output))
{
    // We accumulate the 2 hex digits needed for a byte here
    string h = string.Empty;

    while (true)
    {
        int ch1 = sr.Read();

        if (ch1 == -1)
        {
            // The file finished but we have a pending partial hex code
            if (h.Length == 1)
            {
                throw new Exception("Malformed file");
            }

            break;
        }

        char ch2 = (char)ch1;

        // Skip white space and end-of-line
        if (char.IsWhiteSpace(ch2))
        {
            continue;
        }

        h += ch2;

        // We have collected 2 hex digits, so we have 1 byte
        if (h.Length == 2)
        {
            byte b = Convert.ToByte(h, 16);
            fs.WriteByte(b);
            h = string.Empty;
        }
    }
}

请注意,StreamReaderand File.Create(返回 a FileStream)都做了一些缓冲,因此不需要显式缓冲。我的手在颤抖,因为他们想删除string h缓冲区并直接在byte b. 但我会尽量不要使代码过于复杂:-)


推荐阅读