将.mjpeg文件的十六进制数据另存为C#中的.mjpeg格式文件

时间:2018-07-20 08:21:44

标签: c# arrays codec 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然后是字节数组,但是它也失败了。

任何想法,非常感谢!

凯恩

1 个答案:

答案 0 :(得分:1)

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;
        }
    }
}

请注意,StreamReaderFile.Create(返回FileStream)都进行一些缓冲,因此不需要显式缓冲。我的手在颤抖,因为他们想删除string h缓冲区并直接在byte b中逐个进行十六进制解析。但是,我将尽量不使代码过于复杂:-)