【问题标题】:How to read drawable bits as InputStream如何将可绘制位读取为 InputStream
【发布时间】:2011-09-14 13:37:15
【问题描述】:

据说有一些ImageView 对象。我想将该对象的位/原始数据作为 InputStream 读取。该怎么做?

【问题讨论】:

标签: android imageview inputstream


【解决方案1】:

首先获取ImageView的背景图片作为Drawable的对象:

iv.getBackground();

然后将Drawable图像转换为Bitmap使用

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

现在使用ByteArrayOutputStreamBitmap 转换为Stream 并获得bytearray[];然后 将bytearray 转换为ByteArrayInputStream

您可以使用以下代码从ImageView 获取InputStream

完整的源代码

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

谢谢 迪帕克

【讨论】:

  • 这样重新压缩!
【解决方案2】:

以下这些方法很有用,因为它们适用于任何类型的 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());
}

【讨论】:

  • 它不会重新压缩图像,但是为什么我必须分配位图像素,它占用的内存增加了一倍!
【解决方案3】:

您可以使用绘图缓存来检索任何视图类的位图表示。

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

然后你可以将位图写入一个OutputStream,例如:

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

在您的情况下,我认为您可以使用ByteArrayOutputStream 来获取一个字节[],您可以从中创建一个 InputStream。代码是这样的:

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

【讨论】:

  • 在 Barmaley 提到的问题中,该问题是针对 imageview 的
  • ImageView 显示图像。要捕获任何视图的渲染,包括 ImageView,上面的代码将完成这项工作。
【解决方案4】:

您可能正在寻找这个: openRawResource

【讨论】:

  • 我没有说存储在资源中的图像。我说的是在屏幕上膨胀的 ImageView 对象(所以来源未知)
猜你喜欢
  • 2011-06-25
  • 2017-05-06
  • 1970-01-01
  • 1970-01-01
  • 2021-07-02
  • 1970-01-01
  • 2010-09-23
相关资源
最近更新 更多