Image Uri to bytesarray

user1314243 picture user1314243 · Apr 24, 2012 · Viewed 42.5k times · Source

I have currently have got 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?

Many Thanks

Jake

Answer

user370305 picture user370305 · Apr 24, 2012

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