C# 照片解码成二进制文件:高位在前
以下是用 C# 编写的将一个文件夹内的照片解码转成 bin 文件的程序,照片按照 16 位高位在前来解码:
using System;
using System.IO;
namespace PhotoDecoder
{
class Program
{
static void Main(string[] args)
{
// 文件夹路径
string folderPath = 'D:\Photos';
// 获取文件夹内所有文件路径
string[] filePaths = Directory.GetFiles(folderPath);
// 遍历所有文件
foreach (string filePath in filePaths)
{
// 获取文件名
string fileName = Path.GetFileNameWithoutExtension(filePath);
// 新建输出文件路径,将文件名改为.bin后缀
string outputFilePath = Path.Combine(folderPath, fileName + '.bin');
// 打开输入文件流和输出文件流
using (FileStream input = new FileStream(filePath, FileMode.Open))
using (FileStream output = new FileStream(outputFilePath, FileMode.Create))
{
// 读取文件内容,按照高位在前的方式解码
byte[] buffer = new byte[2];
while (input.Read(buffer, 0, buffer.Length) > 0)
{
ushort value = (ushort)(buffer[1] << 8 | buffer[0]);
byte[] data = BitConverter.GetBytes(value);
output.Write(data, 0, data.Length);
}
}
}
Console.WriteLine('解码完成!');
Console.ReadKey();
}
}
}
在上述代码中,我们使用了 Directory.GetFiles() 方法获取了指定文件夹内所有文件的路径,并使用 Path.GetFileNameWithoutExtension() 方法获取了文件名。然后,我们新建了输出文件路径,并使用 FileStream 打开输入文件流和输出文件流。
在读取文件内容时,我们使用了 byte[] 数组存储读取的数据,并使用位运算和 BitConverter.GetBytes() 方法将两个字节的数据按照高位在前的方式解码成一个无符号短整数。最后,我们使用 output.Write() 方法将解码后的数据写入输出文件流。
当程序运行完成后,我们可以在指定文件夹内找到与输入文件同名的 '.bin' 文件,这个文件就是解码后的二进制文件。
原文地址: https://www.cveoy.top/t/topic/nrbc 著作权归作者所有。请勿转载和采集!