BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeStream(inputStream, null, opts);//此时再将inJustDecodeBounds设false,二次调用decodeStream依然会返回null
Lg.i(TAG, "outHeight:" + opts.outHeight + ",outWidth:" + opts.outWidth + ",outMimeType:" + opts.outMimeType);
inJustDecodeBounds为true时,在解码的时返回的bitmap是null,但可得这个bitmap的尺寸:outHeight和outWidth为该图片的宽高的像素个数,即将图片放大后的方块个数。等于转化成bitmap的getHeight和getWidth值,总字节数为getRowBytes,即2者相乘的结果。getConfig一般为Bitmap.Config.ARGB_8888,即一个像素点占用4bytes空间。(如果bitmap.getHeight()和bitmap.getWidth()都返回100,bitmap.getConfig()返回Bitmap.Config.ARGB_8888,则bitmap.getRowBytes()会返回40000,单位byte字节)。
inSampleSize为2时,一个2000*1000的图片,将被缩小为1000*500,则像素数和内存占用都被缩小为了原来的1/4。
/* 将图片的inputstream流转化成指定倍数的bitmap。如果原图片为100*100个像素点, compressBitmap(is,2)会压缩至50*50个像素点 */
public static Bitmap compressBitmap(InputStream is, int size) {
ByteArrayOutputStream baos = null; //baos.size():1757581字节,即直接从浏览器下载后该图片的大小
BitmapFactory.Options opts = new BitmapFactory.Options();
try {
baos = new ByteArrayOutputStream();
int ch;
while ((ch = is.read()) != -1)
baos.write(ch);
opts.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new ByteArrayInputStream(baos.toByteArray()), null, opts); //此时得到outWidth:1545,outHeight:1545
Log.i(TAG, "baos.size():" + baos.size() + ",outWidth:" + opts.outWidth + ",outHeight:" + opts.outHeight + ",inSampleSize:" + opts.inSampleSize);
//同一张图片,即同一个InputStream,打印日志均为baos.size():1757581,outWidth:1545,outHeight:1545,inSampleSize:0
opts.inSampleSize = size;
opts.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeStream(new ByteArrayInputStream(baos.toByteArray()), null, opts);
Log.i(TAG, "inSampleSize:" + opts.inSampleSize + ",getHeight:" + bitmap.getHeight() + ",getWidth:" + bitmap.getWidth());
return bitmap;
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
baos.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return null;
}
测试上述方法,下载同一张图片,传入不同的倍数,结果返回的bitmap的宽高,并非都=原宽高 / 传入的size。