【发布时间】:2011-09-14 13:37:15
【问题描述】:
据说有一些ImageView 对象。我想将该对象的位/原始数据作为 InputStream 读取。该怎么做?
【问题讨论】:
标签: android imageview inputstream
据说有一些ImageView 对象。我想将该对象的位/原始数据作为 InputStream 读取。该怎么做?
【问题讨论】:
标签: android imageview inputstream
首先获取ImageView的背景图片作为Drawable的对象:
iv.getBackground();
然后将Drawable图像转换为Bitmap使用
BitmapDrawable bitDw = ((BitmapDrawable) d);
Bitmap bitmap = bitDw.getBitmap();
现在使用ByteArrayOutputStream 将Bitmap 转换为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);
谢谢 迪帕克
【讨论】:
以下这些方法很有用,因为它们适用于任何类型的 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());
}
【讨论】:
您可以使用绘图缓存来检索任何视图类的位图表示。
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();
【讨论】:
您可能正在寻找这个: openRawResource
【讨论】: