有人可以帮助编写一个将字节数组转换为二维int数组的方法吗?!
我写过:
internal int[][] byteToInt(byte[] byteArray)
{
int width = (int)Math.Sqrt(byteArray.Length);
int[][] tmp = new int[width][];
for (int i = 0; i < width; i++)
{
tmp[i] = new int[width];
}
for (int i = 0; i < width; i++)
{
for (int j = 0; j < width; j++)
{
tmp[i][j]=(int)byteArray[(i*width+j)];
}
}
return tmp;
}
但这不能正常工作....
答案 0 :(得分:0)
将JPG转换为bytearray的代码:
public byte[] FileToByteArray(string _FileName)
{
byte[] _Buffer = null;
try
{
// Open file for reading
System.IO.FileStream _FileStream = new System.IO.FileStream(_FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
// attach filestream to binary reader
System.IO.BinaryReader _BinaryReader = new System.IO.BinaryReader(_FileStream);
// get total byte length of the file
long _TotalBytes = new System.IO.FileInfo(_FileName).Length;
// read entire file into buffer
_Buffer = _BinaryReader.ReadBytes((Int32)_TotalBytes);
// close file reader
_FileStream.Close();
_FileStream.Dispose();
_BinaryReader.Close();
}
catch (Exception _Exception)
{
// Error
Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
}
return _Buffer;
}
答案 1 :(得分:0)
好的,我认为这会做你想做的事。
如果我理解正确,你想拍摄一张图片并将其转换成一个二维的RGB RGB值数组。
internal int[,] JpgToInt(String fileName)
{
Bitmap Bitmap = new Bitmap(fileName);
int[,] ret = new int[Bitmap.Width,Bitmap.Height];
for (int i = 0; i < Bitmap.Width; i++)
{
for (int j = 0; j < Bitmap.Height; j++)
{
ret[i, j] = Bitmap.GetPixel(i, j).ToArgb();
}
}
return ret;
}
虽然它没有回答主要问题但它确实解决了问题,而问题的解决方案却没有。
在回答主要问题时,没有办法随意取一个字节数组并将其变成一个二维的int数组,因为你不知道二维数组的维数是什么。
用于从文件中获取图像的代码是获取jpg文件的原始二进制文件的正确方法,但它不能自动获取图像。 (参见维基百科how jpeg files are formated)