2012-06-26 54 views
1

有人可以帮助编写一个将字节数组转换为二维int数组的方法吗?将一个字节阵列转换为二维的intarray

我写了:

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

将字节数组放入二维int数组后,有多少个字节之后的条件是什么?如何管理行号/列号? – Habib

+0

发生了什么,你期望它发生了什么? – Dialecticus

+0

我使用QRCode解码器将位图文件转换为int数组。但在WPF中的类位图是不知道的,所以我将我的位图转换为一个bytearray,现在我想将bytearray转换为一个int数组,以便我的程序可以继续... – davidOhara

回答

0

OK,我认为这将做你想要的。

如果我理解正确,您希望拍摄图像并将其转换为int 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; 
} 

虽然它没有回答主要问题,但它确实解决了问题并且问题的解决方案没有。

在回答主要问题时,没有办法任意取一个字节数组并将它变成一个2维int数组,因为您不知道2维数组的维数是多少。

您用来从文件中获取图像的代码是获取jpg文件的原始二进制文件的正确方法,但它不会自行获取图像。 (请参阅how jpeg files are formated的维基百科)

+0

嗨,亚历克斯,yeee,就像一个魅力......但我不能使用位图类,因为WPF不知道它... :( – davidOhara

+0

你好,如何使用它?您将需要有System.Drawing引用。 –

+0

在WPF中,您没有System.Drawing ...那就是我的问题! – davidOhara

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; 
    } 
相关问题