【问题标题】:How to convert video from URI to byte[]如何将视频从 URI 转换为字节 []
【发布时间】:2011-12-16 08:04:26
【问题描述】:

我已经捕获了视频,并获得了该视频的 URI。

如何将该URI指向的内容加载到byte[]结构中?

【问题讨论】:

    标签: java android bytearray


    【解决方案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();
    

    【讨论】:

      【解决方案2】:

      我意识到这个问题已经很老了,但是,我正在寻找一个类似问题的答案,我找到了一种非常简单的方法来做到这一点。请记住,我是在 Kotlin 中执行此操作的,但语法应该非常相似。

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

      File() 采用 URIString。就我而言,我将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
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-04-03
        • 1970-01-01
        • 2020-05-16
        • 1970-01-01
        • 1970-01-01
        • 2020-04-16
        • 2014-04-04
        相关资源
        最近更新 更多