示例代码:
//将图像转换为字节数组 Bitmap bitmap = BitmapFactory.decodeFile("path_to_image"); ByteArrayOutputStream stream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream); byte[] byteArray = stream.toByteArray();
//使用Socket发送图像字节数组 String serverIp = "server_ip_address"; int serverPort = 8888; InetAddress serverAddress = InetAddress.getByName(serverIp); Socket socket = new Socket(serverAddress, serverPort); OutputStream outputStream = socket.getOutputStream();
//写入字节数组到socket输出流 outputStream.write(byteArray); outputStream.flush(); socket.close();
示例代码:
//使用Socket监听客户端连接 IPAddress ipAddress = IPAddress.Any; int port = 8888 TcpListener listener = new TcpListener(ipAddress, port); listener.Start();
//接收客户端连接并读取字节流 TcpClient client = listener.AcceptTcpClient(); NetworkStream networkStream = client.GetStream(); MemoryStream memoryStream = new MemoryStream(); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = networkStream.Read(buffer, 0, buffer.Length)) > 0) { memoryStream.Write(buffer, 0, bytesRead); }
//将字节流转换为图像 byte[] byteArray = memoryStream.ToArray(); Image image; using (MemoryStream ms = new MemoryStream(byteArray)) { image = Image.FromStream(ms); }
//使用图像 pictureBox1.Image = image;
参考链接:https://stackoverflow.com/questions/760561/image-delivery-in-socket-communication-between-android-client-and-c-sharp-serv