Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 263
Barmaley Avatar asked Nov 29 '22 03:11

Barmaley


2 Answers

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

like image 87
Sunil Kumar Sahoo Avatar answered Dec 05 '22 18:12

Sunil Kumar Sahoo


These methods below are useful because they work with any kind of Drawable (not only BitmapDrawable). If you want to use drawing cache as in David Caunt's suggestion, consider using bitmapToInputStream instead of bitmap.compress, because it should be faster.

public static Bitmap drawableToBitmap (Drawable drawable) {
    if (drawable instanceof BitmapDrawable) {
        return ((BitmapDrawable)drawable).getBitmap();
    }

    Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap); 
    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
    drawable.draw(canvas);

    return bitmap;
}

public static InputStream bitmapToInputStream(Bitmap bitmap) {
    int size = bitmap.getHeight() * bitmap.getRowBytes();
    ByteBuffer buffer = ByteBuffer.allocate(size);
    bitmap.copyPixelsToBuffer(buffer);
    return new ByteArrayInputStream(buffer.array());
}
like image 40
André Avatar answered Dec 05 '22 17:12

André