根据所给的uri设置图片:思路是根据uri构建IO流,读取的时候用BitmapFactory的decode系列方法,并用options承载减压后构建新的bitmap对象,最后加载到ImageView控件中。 具体如下: public Bitmap decodeBitmapFromUri(Uri uri, int reqWidth, int reqHeight) { try { // 第一次解析将inJustDecodeBounds设置为true,来获取图片大小 final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(getContentResolver().openInputStream(uri), null, options); // BitmapFactory.decodeResource(res, resId, options); // 调用上面定义的方法计算inSampleSize值 options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // 使用获取到的inSampleSize值再次解析图片 options.inJustDecodeBounds = false; return BitmapFactory.decodeStream(getContentResolver().openInputStream(uri), null, options); } catch (FileNotFoundException e) { e.printStackTrace(); } return null; } public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { // 源图片的高度和宽度 final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { // 计算出实际宽高和目标宽高的比率 final int heightRatio = Math.round((float) height / (float) reqHeight); final int widthRatio = Math.round((float) width / (float) reqWidth); //计算缩放比例 inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; } return inSampleSize; } 最后在加载图片的地方调用Bitmap bitmap = decodeBitmapFromUri(Uri.parse(photoUri), 100, 60); if (bitmap != null) ivPhoto.setImageBitmap(bitmap); 方便的话,可以写一个ImageLoadUtils,并将他们声明为static,这样就可以随心所欲的调用该类的方法了!
图片加载,避免oom篇(1)
最新推荐文章于 2020-12-12 11:48:17 发布