Search code examples
androidimageviewinputstream

How to read drawable bits as InputStream


There's say some ImageView object. I want to read bits/raw data of this object as InputStream. How to do that?


Solution

  • First get background image of the ImageView as an object of Drawable:

    iv.getBackground();
    

    Then convert Drawable image into Bitmap using

    BitmapDrawable bitDw = ((BitmapDrawable) d);
    Bitmap bitmap = bitDw.getBitmap();
    

    Now use ByteArrayOutputStream to get the Bitmap into a Stream and get bytearray[]; then convert the bytearray into a ByteArrayInputStream.

    You can use the following code to get InputStream from ImageView.

    Full Source code

    ImageView iv = (ImageView) findViewById(R.id.splashImageView);
    Drawable d = iv.getBackground();
    BitmapDrawable bitDw = ((BitmapDrawable) d);
    Bitmap bitmap = bitDw.getBitmap();
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
    byte[] imageInByte = stream.toByteArray();
    System.out.println("........length......" + imageInByte);
    ByteArrayInputStream bis = new ByteArrayInputStream(imageInByte);
    

    Thanks Deepak