Because the InputStream Object can only be consumed once, you have to make a deep copy of an InputStream Object when you want to resize the bitmap from inputStream of HttpUrlConnection,otherwise decodeStream will returns null.Here is one possible solution:
HttpURLConnection urlConnection = null;
InputStream in = null;
InputStream in2 = null;
try {
final URL imgUrl = new URL(url);
urlConnection = (HttpURLConnection) imgUrl.openConnection();
in = urlConnection.getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
copy(in,out);
in2 = new ByteArrayInputStream(out.toByteArray());
// resize the bitmap
bitmap = decodeSampledBitmapFromInputStream(in,in2);
} catch (Exception e) {
Log.e(TAG, "Error in down and process Bitmap - " + e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
try {
if (in != null) {
in.close();
}
if (in2 != null){
in2.close();
}
} catch (final IOException e) {
Log.e(TAG, "Error in when close the inputstream." + e);
}
}
}
the souce code of Method copy is as follows:
public static int copy(InputStream input, OutputStream output) throws IOException{
byte[] buffer = new byte[IO_BUFFER_SIZE];
int count = 0;
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += n;
}
return count;
}
the souce code of Method decodeSampledBitmapFromInputStream is as follows:
public static Bitmap decodeSampledBitmapFromInputStream(InputStream in,
InputStream copyOfin, int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(in, null, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeStream(copyOfin, null, options);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…