我在Android上有一个客户端应用程序,在C#上有服务器,他们通过套接字进行通信。 请求服务器发送转换为byte []的图像, 但如何在我的设备上再次将其解码为图像?
我已经找到了这段代码:
Bitmap bmp=BitmapFactory.decodeByteArray(b,0,b.length);
image.setImageBitmap(bmp);
这是客户代码的一部分:
private void connectSocket(String a){
try {
InetAddress serverAddr = InetAddress.getByName("192.168.1.2");
Socket socket = new Socket(serverAddr, 4444);
BufferedReader in = null;
try {
out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.println(message);
String text = "";
image = (ImageView)findViewById(R.id.imageView1);
while ((text = in.readLine()) != null) {
byte[] b = in.readLine().getBytes();
Bitmap bmp=BitmapFactory.decodeByteArray(b,0,b.length);
image.setImageBitmap(bmp);
}
} catch(Exception e) {
Log.e("TCP", "S: Error", e);
} finally {
socket.close();
}
} catch (UnknownHostException e) {
Log.e("TCP", "C: UnknownHostException", e);
e.printStackTrace();
} catch (IOException e) {
Log.e("TCP", "C: IOException", e);
e.printStackTrace();
}
}
那么如何获取确切的接收字节以在图像中转换它们?
答案 0 :(得分:2)
答案 1 :(得分:0)
这是我最终提出的解决方案。我不认为它是对或错,但它在2011年的项目中起作用。不幸的是,我几乎无法记住有关代码的任何细节。希望它有所帮助。
String serverIP = "192.168.0.2";
InetAddress server = InetAddress.getByName(serverIP);
Socket socket = new Socket(server, 4444);
InputStream inStream = socket.getInputStream();
byte[] buffer = new byte[16200]; // extract image from image array
int size = inStream.read(buffer);
byte[] buffer2 = new byte[size];
for(int g = 0; g < size; g++){
buffer2[g] = buffer[g];
}
image = (ImageView) findViewById(R.id.imageView1);
Bitmap bmp = BitmapFactory.decodeByteArray(buffer2, 0, buffer2.length);
image.setImageBitmap(bmp);