如何将可绘制位读取为InputStream

Bar*_*ica 4 android inputstream imageview

有人说有些话ImageView.我想读取此对象的位/原始数据作为InputStream.怎么做?

Sun*_*hoo 14

首先获取imageview的背景图像作为Drawable的对象

iv.getBackground();
Run Code Online (Sandbox Code Playgroud)

然后使用将Drwable图像转换为位图

BitmapDrawable bitDw = ((BitmapDrawable) d);
        Bitmap bitmap = bitDw.getBitmap();
Run Code Online (Sandbox Code Playgroud)

现在使用ByteArrayOutputStream将位图放入流中并获取bytearray []将bytearray转换为ByteArrayInputStream

您可以使用以下代码从imageview获取输入流

完整源代码

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);
Run Code Online (Sandbox Code Playgroud)

谢谢迪帕克


And*_*dré 6

下面的这些方法很有用,因为它们适用于任何类型的 Drawable(不仅仅是 BitmapDrawable)。如果您想按照 David Caunt 的建议使用绘图缓存,请考虑使用bitmapToInputStream代替bitmap.compress,因为它应该更快。

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());
}
Run Code Online (Sandbox Code Playgroud)