-4

Trying to get bytes data from inputstream as shown in the below code. But, the bytes variable is null. What might be the reason? FYI- Image is available in the given uri, as i can see the image in imageView1. (Testing on Lollipop).

final InputStream imageStream = getContentResolver().openInputStream(imageUri);
var_Bitmap = BitmapFactory.decodeStream(imageStream);
ImageView imageView1 = (ImageView) findViewById(R.id.ui_imageView_browse);
imageView1.setImageBitmap(var_Bitmap);
byte[] bytes = IOUtils.toByteArray(imageStream);
OutputStream out;
String root = Environment.getExternalStorageDirectory().getAbsolutePath()+"/";
File createDir = new File(root+"master"+File.separator);
createDir.mkdir();


File file = new File(root + "master" + File.separator +"master.jpg");
path=root+"master"+File.separator+"master.jpg";
file.createNewFile();
out = new FileOutputStream(file);
out.write(bytes);
out.close();
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
djac
  • 187
  • 19
  • 1
    the input stream has been read to the EOF by `decodeStream` so there is nothing to read, why do you want to make a copy of your image anyway? – pskink Aug 10 '17 at 08:39
  • @pskink, thanks, that is the issue.it worked. – djac Aug 10 '17 at 08:45

2 Answers2

1

As pskink suggested in a comment, the issue was that the input stream has been read to the EOF by decodeStream, so there is nothing more to read.

To solve the problem, I created a temporary variable for inputstream.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
djac
  • 187
  • 19
0

Try this :

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

Hope it helps.

Laidi Oussama
  • 108
  • 1
  • 12