Android 图像 Uri 到字节数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10296734/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 03:11:48  来源:igfitidea点击:

Image Uri to bytesarray

androiduribytearray

提问by user1314243

I have currently have got two activities. One for pulling the image from the SD card and one for Bluetooth connection.

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

I have utilized a Bundle to transfer the Uri of the image from activity 1.

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

Now what i wish to do is get that Uri in the Bluetooth activity to and convert it into a transmittable state via Byte Arrays i have seen some examples but i can't seem to get them to work for my code!!

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

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

is what i have to pull it across, What would be the next step?

我必须把它拉过去,下一步是什么?

Many Thanks

非常感谢

Jake

Hyman

回答by user370305

From Urito get byte[]I do the following things,

Uribyte[]我做下面的事情,

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

and the getBytes(InputStream)method is:

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

回答by Peter F

Kotlin is very concise here:

Kotlin 在这里非常简洁:

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

In Kotlin, they added convenient extension functions for InputStreamlike buffered,use, and readBytes.

在科特林,他们增加了便捷的扩展功能InputStream一样bufferedusereadBytes

  • buffereddecorates the input stream as BufferedInputStream
  • usehandles closing the stream
  • readBytesdoes the main job of reading the stream and writing into a byte array
  • buffered将输入流装饰为 BufferedInputStream
  • use处理关闭流
  • readBytes主要工作是读取流并写入字节数组

Error cases:

错误案例:

  • IOExceptioncan occur during the process (like in Java)
  • openInputStreamcan return null. If you call the method in Java you can easily oversee this. Think about how you want to handle this case.
  • IOException可能在此过程中发生(如在 Java 中)
  • openInputStream可以返回null。如果您在 Java 中调用该方法,您可以轻松地监督这一点。想想你想如何处理这个案例。

回答by ahmed_khan_89

Java best practice: never forget to close every stream you open! This is my implementation:

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

回答by LSA

Syntax in kotlin

kotlin 中的语法

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

回答by krupesh halarnkar

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

回答by Shankar Agarwal

use getContentResolver().openInputStream(uri) to get an InputStream from a URI. and then read the data from inputstream convert the data into byte[] from that inputstream

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

Try with following code

尝试使用以下代码

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

Refer this LINKs

参考这个链接

回答by png

This code works for me

这段代码对我有用

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