简体   繁体   English

发送图像套接字io和android

[英]Send image socket io and android

I am a beginner in socket.io. 我是socket.io的初学者。 I have been used a library 我已经用过图书馆

https://www.npmjs.com/package/socket.io-stream https://www.npmjs.com/package/socket.io-stream

We were successfully uploaded images using the browser. 我们已经使用浏览器成功上传了图像。 But now, I want to upload images from android application. 但是现在,我想从android应用程序上传图像。 If anyone have android code please give me .. 如果有人有Android代码,请给我..

https://github.com/socketio/socket.io-client-java/issues/29 https://github.com/socketio/socket.io-client-java/issues/29

I have been searching on google, but not found any proper solution. 我一直在谷歌上搜索,但找不到任何合适的解决方案。

   var imageBuffer = customJs.decodeBase64Image(base64Data);
   var imageTypeDetected = imageBuffer.type.match(/\/(.*?)$/);
   var filename = 'profile-' + Date.now() + '.' + imageTypeDetected[1];
   // config.uploadImage --- Folder path where you want to save.
   var uploadedImagePath = config.uploadImage + filename;
   try {
       fs.writeFile(uploadedImagePath, imageBuffer.data, function () {
       dbMongo.updateImage({email: decoded.email, user_id: decoded.userId, 'profile_picture': config.showImagePath + filename}, function (res) {
       if (res.error) { 
       socket.emit('set_update_image', {'error': 1, 'message': 'Error!' + res.message, 'data': null, 'status': 400});
       } else {
         console.log(res);
         socket.emit('set_update_image', res);
       }
       });
     });
      } catch (e) {
           socket.emit('set_update_image', {'error': 1, 'message': 'Internal server error ' + e, 'data': null, 'status': 400});
      }

From other file call a function 从其他文件调用函数

exports.decodeBase64Image = function decodeBase64Image(dataString) {
var matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/);
var response = {};

if (matches.length !== 3)
{
    return new Error('Invalid input string');
}

response.type = matches[1];
response.data = new Buffer(matches[2], 'base64');

return response;
}

For the upload image from android using socket you need to send image as base64 string, 对于使用套接字从Android上传图片,您需要将图片作为base64字符串发送,

Following is the example for convert Image into base64 then you send data same as another paramaters. 以下是将Image转换为base64然后发送与另一个参数相同的数据的示例。

String base64Image = getBase64Data(dirPath + "/" + fileName);

public String getBase64Data(String filePath) {
        try {
            InputStream inputStream = new FileInputStream(filePath);//You can get an inputStream using any IO API
            byte[] bytes;
            byte[] buffer = new byte[8192];
            int bytesRead;
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            try {
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    output.write(buffer, 0, bytesRead);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            bytes = output.toByteArray();
            return "data:image/jpeg;base64," + Base64.encodeToString(bytes, Base64.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

In android, you need to encode the image by using Base64 在android中,您需要使用Base64对图像进行编码

 public void sendImage(String path)
 {
    JSONObject sendData = new JSONObject();
    try{
          sendData.put("imageData", encodeImage(path));
          socket.emit("image",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;
}

In server side, receive image and decode it 在服务器端,接收图像并将其解码

socket.on("image", function(info) {
    var img = new Image();
    img.src = 'data:image/jpeg;base64,' + info.imageData;

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM