案例说明php
案例分析android
网络图片计算Bitmap的内存大小git
加载本地资源计算Bitmap的内存大小程序员
正确说法,这个注意呢?计算公式以下所示github
影响Bitmap占用内存的因素:segmentfault
获取图像的来源通常有三种源头:微信
针对这三种状况咱们通常使用BitmapFactory的网络
思考一下:内存去哪里了(为何被消耗了这么多)?ide
为什么容易OOM?函数
如今图片的大小已经知道了,咱们就能够决定是把整张图片加载到内存中仍是加载一个压缩版的图片到内存中。如下几个因素是咱们须要考虑的:
怎样才能对图片进行压缩呢?
好比咱们有一张2048x1536像素的图片,将inSampleSize的值设置为4,就能够把这张图片压缩成512x384像素。
下面的方法能够根据传入的宽和高,计算出合适的inSampleSize值:
public static 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的值,这样能够保证最终图片的宽和高 // 必定都会大于等于目标的宽和高。 inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; } return inSampleSize; }
大概步骤以下所示
具体的实现代码
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) { // 第一次解析将inJustDecodeBounds设置为true,来获取图片大小 final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResource(res, resId, options); // 调用上面定义的方法计算inSampleSize值 options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // 使用获取到的inSampleSize值再次解析图片 options.inJustDecodeBounds = false; return BitmapFactory.decodeResource(res, resId, options); }
思考:inJustDecodeBounds这个参数是干什么的?
为什么设置两次inJustDecodeBounds属性?
将任意一张图片压缩成100*100的缩略图,并在ImageView上展现。
mImageView.setImageBitmap( decodeSampledBitmapFromResource(getResources(), R.id.ycimage, 100, 100));