Search code examples
androidarraysuri

Image Uri to bytesarray


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?


Solution

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