How to convert video from URI to byte[]

2019-08-10 23:14发布

问题:

I have captured video and I get a URI of that video.

How to load the content pointed to by that URI into byte[] structure?

回答1:

Have a look at

  • ByteArrayOutputStream,
  • FileInputStream, and
  • File(URI uri).

Code example:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
FileInputStream fis = new FileInputStream(new File(yourUri));

byte[] buf = new byte[1024];
int n;
while (-1 != (n = fis.read(buf)))
    baos.write(buf, 0, n);

byte[] videoBytes = baos.toByteArray();


回答2:

I realize this question is very old, however, I was searching for an answer to a similiar question and I found a very simple way to do this. Bear in mind I did this in Kotlin but the syntax should be very similiar.

val videoBytes = FileInputStream(File(videoPath)).use { input -> input.readBytes() }

File() takes a URI or String. In my case I converted the Uri to String.

Using FileInputStream().use {} will also close the input stream.

The code below is the method I used to convert the Uri into a String:

    private fun getVideoPathFromURI(uri: Uri): String
{
    var path: String = uri.path // uri = any content Uri

    val databaseUri: Uri
    val selection: String?
    val selectionArgs: Array<String>?
    if (path.contains("/document/video:"))
    { // files selected from "Documents"
        databaseUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI
        selection = "_id=?"
        selectionArgs = arrayOf(DocumentsContract.getDocumentId(uri).split(":")[1])
    }
    else
    { // files selected from all other sources, especially on Samsung devices
        databaseUri = uri
        selection = null
        selectionArgs = null
    }
    try
    {
        val projection = arrayOf(
            MediaStore.Video.Media.DATA,
            MediaStore.Video.Media._ID,
            MediaStore.Video.Media.LATITUDE,
            MediaStore.Video.Media.LONGITUDE,
            MediaStore.Video.Media.DATE_TAKEN)

        val cursor = contentResolver.query(databaseUri,
            projection, selection, selectionArgs, null)

        if (cursor.moveToFirst())
        {
            val columnIndex = cursor.getColumnIndex(projection[0])
            videoPath = cursor.getString(columnIndex)
        }
        cursor.close()
    }
    catch (e: Exception)
    {
        Log.e("TAG", e.message, e)
    }
    return videoPath
}