2016-06-15 37 views
0

ソケットを介してiOSからUnityにUIImageを送信しようとしています。 UIImageをNSDataに変換し、非同期ソケット経由でUnityのサーバに送信します。iOSのUnity C#でソケットから画像をバイト単位で受信

クライアント(iOSアプリ)からすべてのバイトを受け取り、これらのバイトをイメージに変換してイメージとしてコンピュータに保存しようとしています。私はファイルのすべての時間エラーを取得している、空または破損しています。

iOS側、Unity側、またはその両方でエラーが発生するかどうかはわかりません。 Unityシステム側で

UIImage *img = images[number]; 
NSData *dataImg = UIImagePNGRepresentation(img); 
[asyncSocket writeData:dataImg withTimeout:-1 tag:1]; // Uses GCDA Async Socket library 
[asyncSocket disconnectAfterWriting]; 

、私が持っている:私のiOS側で

、私が持っている空

// Data buffer for incoming data. 
    byte[] bytes = new Byte[1024]; 

    // host running the application. 
    Debug.Log("Ip " + getIPAddress().ToString()); 
    IPAddress[] ipArray = Dns.GetHostAddresses(getIPAddress()); 
    IPEndPoint localEndPoint = new IPEndPoint(ipArray[0], 1755); 

    // Create a TCP/IP socket. 
    listener = new Socket(ipArray[0].AddressFamily, 
          SocketType.Stream, ProtocolType.Tcp); 

    // Bind the socket to the local endpoint and 
    // listen for incoming connections. 

    try 
    { 
     listener.Bind(localEndPoint); 
     listener.Listen(10); 

     // Start listening for connections. 
     while (true) 
     { 
      Debug.Log("Client Connected"); 

      Socket handler = listener.Accept(); 

      while (true) { 
       bytes = new byte[1024]; 
       int bytesRec = handler.Receive(bytes); 
       data += Encoding.ASCII.GetString(bytes,0,bytesRec); 

       Debug.Log("Bytes rec: " + bytesRec); 
       if (bytesRec <= 0) { 

        // Save image in folder from bytes 
        File.WriteAllBytes(@"images/img.png",bytes); 

        break; 
       } 

      } 

      //File.WriteAllBytes(@"images/prova.png",dataImg); 

      System.Threading.Thread.Sleep(1); 
     } 
    } 
    catch (Exception e) 
    { 
     Debug.Log(e.ToString()); 
    } 
} 

答えて

0

をされるか、または破損

bytes = new byte[1024];

ではありません平均的な画像を保持するのに十分です。 1024から400,000までバンプします。また bytes = new byte[400000];

でなければなりません

は、それはあなたがこれを行う場合は、満たされていなかった他のバイトもPNGファイルので、このかもしれない破損したファイルに書き込まれます見えます。これを修正するには

byte []newImage = new byte[bytesRec]; 
Array.Copy(bytes, newImage, bytesRec); 
System.IO.File.WriteAllBytes(@"images/img.png", bytes); 

それが動作するかどうか。これは、後に向上させることが可能と

System.IO.File.WriteAllBytes(@"images/img.png", bytes); 

を交換してください。

関連する問題