[英]How to send image file(binary data) using socket.io?
I have trouble to sending data from Android Client
to NodeJS Server
. 我无法将数据从Android Client
发送到NodeJS Server
。
I use Socket.IO-client java library in my client. 我在客户端使用Socket.IO-client java库。
But, there is not much information for me. 但是,对我来说没有太多信息。
How can i sending binary data from android client to nodejs server? 如何从android客户端向nodejs服务器发送二进制数据?
You can use Base64 to encode the image: 您可以使用Base64 对图像进行编码 :
public void sendImage(String path)
{
JSONObject sendData = new JSONObject();
try{
sendData.put("image", encodeImage(path));
socket.emit("message",sendData);
}catch(JSONException e){
}
}
private String encodeImage(String path)
{
File imagefile = new File(path);
FileInputStream fis = null;
try{
fis = new FileInputStream(imagefile);
}catch(FileNotFoundException e){
e.printStackTrace();
}
Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG,100,baos);
byte[] b = baos.toByteArray();
String encImage = Base64.encodeToString(b, Base64.DEFAULT);
//Base64.de
return encImage;
}
So basically you are sending a string to node.js 所以基本上你要向node.js发送一个字符串
If you want to receive the image just decode in Base64: 如果你想接收图像只需在Base64中解码 :
private Bitmap decodeImage(String data)
{
byte[] b = Base64.decode(data,Base64.DEFAULT);
Bitmap bmp = BitmapFactory.decodeByteArray(b,0,b.length);
return bmp;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.