使用inputStreamToByteArray方法将InputStream解析为byte[]:
public byte[] inputStreamToByteArray(InputStream inputStream) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) > -1) {
baos.write(buffer, 0, len);
}
baos.flush();
return baos.toByteArray();
}
在加载大型位图时,请考虑 Google 的建议。根据您的需要调整它们的大小。通过这样做,您将防止许多内存故障:
private Bitmap getBitmap(InputStream is, int requestedMaxWidth, int requestedMaxHeight) throws IOException {
// parse inputStream to byte[]
byte[] dataToBeDecode = inputStreamToByteArray(is);
BitmapFactory.Options options = new BitmapFactory.Options();
// First see the width and height of incoming bitmap
options.inJustDecodeBounds = true;
BitmapFactory.decodeByteArray(dataToBeDecode, 0, dataToBeDecode.length, options);
// Calculate inSampleSize for resizing
options.inSampleSize = calculateInSampleSize(options, requestedMaxWidth, requestedMaxHeight);
// Now resize and get the bitmap
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeByteArray(dataToBeDecode, 0, dataToBeDecode.length, options);
return bitmap;
}
public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2
// and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
编辑:阅读 Google 的加载大型位图文档。 See link.