图像Uri到字节数组

时间:2012-04-24 11:10:47

标签: android uri bytearray

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

我利用Bundle从活动1转移图像的Uri。

现在我想要做的是将蓝牙活动中的Uri转换为并通过Byte Arrays将其转换为可传输状态我已经看到了一些示例但我似乎无法让它们为我的代码工作!! / p>

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

是我必须解决的问题,下一步是什么?

非常感谢

杰克

7 个答案:

答案 0 :(得分:75)

Uribyte[]我做了以下事情,

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

答案 1 :(得分: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;
}

答案 2 :(得分:0)

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

尝试使用以下代码

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

参考此链接

答案 3 :(得分:0)

此代码适用于我

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

答案 4 :(得分:0)

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

答案 5 :(得分:0)

科特琳在这里非常简洁:

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

在Kotlin中,他们为InputStreambufferedusereadBytes添加了方便的扩展功能。

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

错误情况:

  • IOException可能会在此过程中发生(例如在Java中)
  • openInputStream可以返回null。如果您使用Java调用该方法,则可以轻松地对此进行监督。考虑一下您要如何处理这种情况。

答案 6 :(得分:0)

科特林的语法

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