mercredi 27 mai 2015

How do I get a video from URI and compress it and convert it into base64 and send it to the server on Android?

I want to capturing video and sending it to the server in base64. Before sending it, I want to check the video length and video size. I am able to capture the video

        switch (v.getId()) {
            case R.id.camera_button:
                intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
                if (intent.resolveActivity(getPackageManager()) != null) {
                    startActivityForResult(intent, INTENT_VIDEO);
                }
                break;
            }
        }

and get the URI

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == INTENT_VIDEO && resultCode == RESULT_OK) {
            Uri uri = data.getData();
            videoView.setVideoURI(uri);
            videoView.start();
        }
    }

I am able to get a video path

    private String getPath(Uri video) {
        String path = video.getPath();
        String[] projection = {MediaStore.Video.Media.DATA};
        Cursor cursor = getContentResolver().query(media, projection, null, null, null);
        if (cursor.moveToFirst()) path = cursor.getString(cursor.getColumnIndexOrThrow(projection[0]));
        cursor.close();

        return path;
    }

How do I get a video object from that path so that I could compress, check video duration, file size? For image, it will be as simple as this BitmapFactory.decodeFile(photoPath);

and after that, I would like to convert it to base64. For image, it's as simple as this

    private String toBase64(Bitmap bitmap) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 60, outputStream);
        byte[] bytes = outputStream.toByteArray();

        return Base64.encodeToString(bytes, Base64.DEFAULT);
    }

Currently I am doing like this

    private String toBase64(Uri video) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            String path = getPath(video);
            File tmpFile = new File(path);
            BufferedInputStream in = new BufferedInputStream(new FileInputStream(tmpFile));
            long length = tmpFile.length();
            int inLength = (int) length;
            byte[] b = new byte[inLength];
            int bytesRead;
            while ((bytesRead = in.read(b)) != -1) {
                baos.write(b, 0, bytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT);
    }

I get the base64, though I don't know if it's the correct one. but, I could not check video size, duration, etc. and also when I try to send the base64 to the server, I get error Unexpected response code 500.

Aucun commentaire:

Enregistrer un commentaire