How to read drawable bits as InputStream

安稳与你 提交于 2019-12-30 05:13:06

问题


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


回答1:


First get Background image of the imageview as an object of Drawable

iv.getBackground();

Then convert Drwable image into bitmap using

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

Now use ByteArrayOutputStream to get the bitmap into the stream and get bytearray[] convert bytearray into 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




回答2:


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



回答3:


You can use the drawing cache to retrieve a Bitmap representation of any View class.

view.setDrawingCacheEnabled(true);
Bitmap b = view.getDrawingCache();

Then you can write the bitmap to an OutputStream, for example:

b.compress(CompressFormat.JPEG, 80, new FileOutputStream("/view.jpg"));

In your case I think you can use a ByteArrayOutputStream to get a byte[] from which you can create an InputStream. The code would be something like this:

ByteArrayOutputStream os = new ByteArrayOutputStream(b.getByteCount());
b.compress(CompressFormat.JPEG, 80, os);
byte[] bytes = os.toByteArray();



回答4:


You might be looking for this: openRawResource



来源:https://stackoverflow.com/questions/6341770/how-to-read-drawable-bits-as-inputstream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!