我正在尝试通过套接字从iOS向Unity发送UIImage
。我将UIImage
转换为NSData
并通过异步套接字将其发送到Unity中的服务器。
我正在尝试从客户端(iOS应用程序)接收所有字节并将这些字节转换为图像并将其作为图像保存在计算机中。我得到文件的所有时间错误,要么是空的,要么是损坏的。
我不知道在iOS端,Unity端或两者都是错误。
在我的iOS方面,我有:
UIImage *img = images[number];
NSData *dataImg = UIImagePNGRepresentation(img);
[asyncSocket writeData:dataImg withTimeout:-1 tag:1]; // Uses GCDA Async Socket library
[asyncSocket disconnectAfterWriting];
在Unity方面,我有:
// 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 :(得分:0)
是空的还是已损坏的
bytes = new byte[1024];
不足以保持平均图像。 Bump 1024最多400,000。
那应该是bytes = new byte[400000];
此外,它看起来如果你这样做,其他未填充的字节也将被写入文件,因此这可能会破坏png文件。
要解决此问题,请替换
System.IO.File.WriteAllBytes(@"images/img.png", bytes);
与
byte []newImage = new byte[bytesRec];
Array.Copy(bytes, newImage, bytesRec);
System.IO.File.WriteAllBytes(@"images/img.png", bytes);
如果有效,可以在以后改进。