我已经捕获了视频,并获得了该视频的URI。
如何将该URI指向的内容加载到byte[]
结构中?
答案 0 :(得分:1)
看看
代码示例:
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();
答案 1 :(得分:0)
我意识到这个问题很老,但是,我正在寻找类似问题的答案,因此我找到了一种非常简单的方法来解决这个问题。请记住,我是在Kotlin中这样做的,但是语法应该非常相似。
val videoBytes = FileInputStream(File(videoPath)).use { input -> input.readBytes() }
File()
取URI
或String
。就我而言,我将Uri
转换为String
。
使用FileInputStream().use {}
也将关闭输入流。
下面的代码是我用来将Uri
转换为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
}