我已在两个Android设备之间建立WiFi连接。现在我想将Bitmap从服务器发送到客户端。我使用以下代码将Bitmap从服务器发送到客户端:
服务器代码:
outputStream = hostThreadSocket.getOutputStream();
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 20,stream);
byte[] byteArray = stream.toByteArray();
String str =Base64.encodeToString(byteArray,0);
msgReply+=" "+str;
outputStream.write(str.getBytes());
outputStream.flush();
outputStream.close();
客户代码:
socket = new Socket(dstAddress, dstPort);
ByteArrayOutputStream byteArrayOutputStream =
new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = socket.getInputStream();
while ((bytesRead = inputStream.read(buffer)) != -1){
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString();
}
byte[] temp_arr = new byte[1024];
String[] safe = response.split("=");
try{
temp_arr=Base64.decode(safe[0], 0);
}catch (Exception e){
e.printStackTrace();
}
Bitmap bmp = BitmapFactory.decodeByteArray(temp_arr,0,temp_arr.length);
ImageView img=(ImageView)findViewById(R.id.imgView);
img.setImageBitmap(bmp);