【问题标题】:Save hex datas of .mjpeg file as a .mjpeg formatted file in C#在 C# 中将 .mjpeg 文件的十六进制数据保存为 .mjpeg 格式的文件
【发布时间】:2018-07-20 08:21:43
【问题描述】:

我有一个填充了 .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# arrays codec mjpeg


    【解决方案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 中逐个十六进制数字地解析十六进制数字。但我会尽量不要使代码过于复杂:-)

    【讨论】:

    • 出色的工作!它完美地工作。太感谢了!! :)
    猜你喜欢
    • 2018-12-26
    • 2021-07-11
    • 2011-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-15
    • 1970-01-01
    • 2015-01-26
    相关资源
    最近更新 更多