这里有一个 ImageView
对象。我想要将其位/原始数据作为 InputStream 读取。如何实现呢?
这里有一个 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);
谢谢 Deepak
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();
b.compress(CompressFormat.JPEG, 80, new FileOutputStream("/view.jpg"));
在您的情况下,我认为您可以使用ByteArrayOutputStream来获取一个byte[],从中可以创建一个InputStream。代码应该像这样:
ByteArrayOutputStream os = new ByteArrayOutputStream(b.getByteCount());
b.compress(CompressFormat.JPEG, 80, os);
byte[] bytes = os.toByteArray();