/** * 根据图片的url路径获得Bitmap对象, 有压缩效果的,占用内存小了, * @param url * @return */ public static Bitmap returnBitmap(String url) { URL fileUrl = null; Bitmap bitmap = null; try { fileUrl = new URL(url); } catch (MalformedURLException e) { e.printStackTrace(); } try { HttpURLConnection conn = (HttpURLConnection) fileUrl .openConnection(); conn.setDoInput(true); conn.connect(); //-------------------------------------------------------------------- rhj add 20200106 BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 4; //压缩占用内存大小, 采样率压缩,,把图片尺寸缩小了 可以缩小20倍左右内存 options.inPreferredConfig = Bitmap.Config.RGB_565; // 色彩值压缩。压缩占用内存大小 可缩小一半内存 //-------------------------------------------------------------------- rhj add 20200106 InputStream is = conn.getInputStream(); // bitmap = BitmapFactory.decodeStream(is); // 旧的无参数配置的流,不压缩处理 //-------------------------------------------------------------------- rhj add 20200106 bitmap = BitmapFactory.decodeStream(is,null,options); // // // 查看bitmap大小 rhj add 20200106 LogUtil.e(TAG,"第一次压缩,options配置压缩,returnBitmap() 图片bitmap size(K) 2222: " + BitmapUtil.getBitmapSize(bitmap) + " K ,,size(M): " + BitmapUtil.getBitmapSize(bitmap)/1024 + "M"); // // 查看bitmap大小 rhj add 20200106 // LogUtil.e(TAG,"第二次压缩,compress压缩,returnBitmap() 图片bitmap size(K) 2222: " // + BitmapUtil.getBitmapSize(bitmap) + " K ,,size(M): " // + BitmapUtil.getBitmapSize(bitmap)/1024 + "M"); //-------------------------------------------------------------------- rhj add 20200106 is.close(); return bitmap; } catch (Exception e) { e.printStackTrace(); } return bitmap; }
/** * 获取 Bitmap 的大小 */ public static int getBitmapSize(Bitmap bitmap) { if (bitmap == null){ return 0; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { //API 19 return bitmap.getAllocationByteCount() / 1024; //k } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {//API 12 return bitmap.getByteCount() / 1024; //k } // 其他版本return bitmap 的大小 return bitmap.getRowBytes() * bitmap.getHeight() / 1024; //k //earlier version }