如何在Android上压缩来自URI的视频?

时间:2015-05-28 05:42:43

标签: android android-intent

我想捕获视频并将其发送到base64中的服务器。在发送之前,我想检查视频长度和视频大小。我能够捕捉视频

        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;
            }
        }

并获取URI

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

我能够获得视频路径

    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;
    }

如何从该路径获取视频对象,以便我可以压缩,检查视频持续时间,文件大小? 对于图像,它将如此简单 BitmapFactory.decodeFile(photoPath);

之后,我想将其转换为base64。 对于图像,它就像这个

一样简单
    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);
    }

目前我正在这样做

    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);
    }

我得到了base64,但我不知道它是否是正确的。但是,我无法检查视频大小,持续时间等。

0 个答案:

没有答案