Image Uri to bytesarray

AndroidArraysUri

Android Problem Overview


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

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

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!!

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

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

Android Solutions


Solution 1 - Android

From Uri to get byte[] I do the following things,

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

and the getBytes(InputStream) method is:

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

Solution 2 - Android

Kotlin is very concise here:

@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 InputStream like buffered,use , and readBytes.

  • buffered decorates the input stream as BufferedInputStream
  • use handles closing the stream
  • readBytes does the main job of reading the stream and writing into a byte array

Error cases:

  • IOException can occur during the process (like in Java)
  • openInputStream can return null. If you call the method in Java you can easily oversee this. Think about how you want to handle this case.

Solution 3 - Android

Syntax in kotlin

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

Solution 4 - Android

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

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

Solution 5 - Android

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

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

Solution 6 - Android

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

Solution 7 - Android

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

Solution 8 - Android

Use the following method to create a bytesArray from a URI in Android studio.

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1314243View Question on Stackoverflow
Solution 1 - Androiduser370305View Answer on Stackoverflow
Solution 2 - AndroidPeter FView Answer on Stackoverflow
Solution 3 - AndroidLSAView Answer on Stackoverflow
Solution 4 - Androidahmed_khan_89View Answer on Stackoverflow
Solution 5 - AndroidShankar AgarwalView Answer on Stackoverflow
Solution 6 - AndroidpngView Answer on Stackoverflow
Solution 7 - Androidkrupesh halarnkarView Answer on Stackoverflow
Solution 8 - AndroidCodemakerView Answer on Stackoverflow