如何使用socket.io发送图像文件(二进制数据)?

4

我在将数据从Android客户端发送到NodeJS服务器时遇到了麻烦。

我在客户端使用Socket.IO-client Java库。

但是,对于我来说没有太多信息。

我如何将二进制数据从Android客户端发送到NodeJS服务器?

1个回答

10

你可以使用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;

    }

基本上你是在将一个字符串发送到node.js

如果你想接收图像,只需在Base64中解码:

private Bitmap decodeImage(String data)
{
    byte[] b = Base64.decode(data,Base64.DEFAULT);
    Bitmap bmp = BitmapFactory.decodeByteArray(b,0,b.length);
    return bmp;
}    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接