【问题标题】:Image Uri to bytesarray图像 Uri 到字节数组
【发布时间】:2012-05-05 00:29:11
【问题描述】:

我目前有两个活动。一种用于从 SD 卡中提取图像,另一种用于蓝牙连接。

我已经使用 Bundle 从活动 1 中传输图像的 Uri。

现在我想做的是让蓝牙活动中的 Uri 通过字节数组将其转换为可传输状态我已经看到了一些示例,但我似乎无法让它们为我的代码工作!!

Bundle goTobluetooth = getIntent().getExtras();
    test = goTobluetooth.getString("ImageUri");

是我必须克服的。下一步是什么?

【问题讨论】:

    标签: android arrays uri


    【解决方案1】:

    Uri得到byte[]我做了以下事情,

    InputStream iStream =   getContentResolver().openInputStream(uri);
    byte[] inputData = getBytes(iStream);
    

    getBytes(InputStream) 方法是:

    public byte[] getBytes(InputStream inputStream) throws IOException {
          ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
          int bufferSize = 1024;
          byte[] buffer = new byte[bufferSize];
    
          int len = 0;
          while ((len = inputStream.read(buffer)) != -1) {
            byteBuffer.write(buffer, 0, len);
          }
          return byteBuffer.toByteArray();
        }
    

    【讨论】:

    • getContentResolver().openInputStream(test);收到一条错误消息,指出它不适用于字符串的参数!!参考我在其状态之上的代码,uri 是字符串形式,我该如何更改它以与您上面所述的代码一致!
    • test 是一个字符串变量,你必须通过 Uri。从测试中制作 Uri,然后将其传递给方法..
    • 仍然收到错误提示 uri 无法解析为变量!!
    • 你要写这行,InputStream iStream = getContentResolver().openInputStream(Uri.parse(test));
    • InputStream iStream =... 行给了我FileNotFoundException
    【解决方案2】:

    Kotlin 在这里非常简洁:

    @Throws(IOException::class)
    private fun readBytes(context: Context, uri: Uri): ByteArray? = 
        context.contentResolver.openInputStream(uri)?.buffered()?.use { it.readBytes() }
    

    在 Kotlin 中,他们为 InputStream 添加了方便的扩展函数,例如 bufferedusereadBytes

    • buffered 将输入流装饰为 BufferedInputStream
    • use 处理关闭流
    • readBytes 主要负责读取流并写入字节数组

    错误案例:

    • IOException 可以在过程中发生(就像在 Java 中一样)
    • openInputStream 可以返回null。如果您在 Java 中调用该方法,您可以轻松地监督这一点。考虑一下您想如何处理这种情况。

    【讨论】:

      【解决方案3】:

      Java 最佳实践:永远不要忘记关闭您打开的每个流! 这是我的实现:

      /**
       * get bytes array from Uri.
       * 
       * @param context current context.
       * @param uri uri fo the file to read.
       * @return a bytes array.
       * @throws IOException
       */
      public static byte[] getBytes(Context context, Uri uri) throws IOException {
          InputStream iStream = context.getContentResolver().openInputStream(uri);
          try {
              return getBytes(iStream);
          } finally {
              // close the stream
              try {
                  iStream.close();
              } catch (IOException ignored) { /* do nothing */ }
          }
      }
      
      
      
       /**
       * get bytes from input stream.
       *
       * @param inputStream inputStream.
       * @return byte array read from the inputStream.
       * @throws IOException
       */
      public static byte[] getBytes(InputStream inputStream) throws IOException {
      
          byte[] bytesResult = null;
          ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
          int bufferSize = 1024;
          byte[] buffer = new byte[bufferSize];
          try {
              int len;
              while ((len = inputStream.read(buffer)) != -1) {
                  byteBuffer.write(buffer, 0, len);
              }
              bytesResult = byteBuffer.toByteArray();
          } finally {
              // close the stream
              try{ byteBuffer.close(); } catch (IOException ignored){ /* do nothing */ }
          }
          return bytesResult;
      }
      

      【讨论】:

        【解决方案4】:

        kotlin 中的语法

        val inputData = contentResolver.openInputStream(uri)?.readBytes()
        

        【讨论】:

          【解决方案5】:

          使用 getContentResolver().openInputStream(uri) 从 URI 获取 InputStream。然后从输入流中读取数据将数据从该输入流转换为字节[]

          试试下面的代码

          public byte[] readBytes(Uri uri) throws IOException {
                    // this dynamically extends to take the bytes you read
                  InputStream inputStream = getContentResolver().openInputStream(uri);
                    ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
          
                    // this is storage overwritten on each iteration with bytes
                    int bufferSize = 1024;
                    byte[] buffer = new byte[bufferSize];
          
                    // we need to know how may bytes were read to write them to the byteBuffer
                    int len = 0;
                    while ((len = inputStream.read(buffer)) != -1) {
                      byteBuffer.write(buffer, 0, len);
                    }
          
                    // and then we can return your byte array.
                    return byteBuffer.toByteArray();
                  }
          

          参考此链接

          【讨论】:

          • 你的答案和我的有什么区别?
          • 方法名:)
          【解决方案6】:

          这段代码对我有用

          Uri selectedImage = imageUri;
                      getContentResolver().notifyChange(selectedImage, null);
                      ImageView imageView = (ImageView) findViewById(R.id.imageView1);
                      ContentResolver cr = getContentResolver();
                      Bitmap bitmap;
                      try {
                           bitmap = android.provider.MediaStore.Images.Media
                           .getBitmap(cr, selectedImage);
          
                          imageView.setImageBitmap(bitmap);
                          Toast.makeText(this, selectedImage.toString(),
                                  Toast.LENGTH_LONG).show();
                          finish();
                      } catch (Exception e) {
                          Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
                                  .show();
          
                          e.printStackTrace();
                      }
          

          【讨论】:

            【解决方案7】:
            public void uriToByteArray(String uri)
                {
            
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    FileInputStream fis = null;
                    try {
                        fis = new FileInputStream(new File(uri));
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
            
                    byte[] buf = new byte[1024];
                    int n;
                    try {
                        while (-1 != (n = fis.read(buf)))
                            baos.write(buf, 0, n);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    byte[] bytes = baos.toByteArray();
                }
            

            【讨论】:

              【解决方案8】:

              在 Android Studio 中使用以下方法从 URI 创建一个 bytesArray

              public byte[] getBytesArrayFromURI(Uri uri) {
                  try {
                      InputStream inputStream = getContentResolver().openInputStream(uri);
                      ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
                      int bufferSize = 1024;
                      byte[] buffer = new byte[bufferSize];
              
                      int len = 0;
                      while ((len = inputStream.read(buffer)) != -1) {
                          byteBuffer.write(buffer, 0, len);
                      }
              
                      return byteBuffer.toByteArray();
              
                  }catch(Exception e) {
                      Log.d("exception", "Oops! Something went wrong.");
                  }
                  return null;
              }
              

              【讨论】:

                猜你喜欢
                • 2017-09-30
                • 2012-07-28
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2023-03-15
                • 1970-01-01
                • 2010-12-07
                相关资源
                最近更新 更多