Android加载一张3.4MB的图片,不出现OOM

package com.jianda.zuci.showbigphoto;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {

    private ImageView iv_bigPhoto;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        iv_bigPhoto = (ImageView)findViewById(R.id.iv_bigPhoto);
        int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);//得到系统内存大小
        Log.v("maxMemory",maxMemory+"KB");

        iv_bigPhoto.setImageBitmap(decodeSampledBitmapFromResource(getResources(),R.drawable.bigphoto,256,144));



    }

    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 set to a value > 1, requests the decoder to subsample the original image, returning a smaller image to save memory.
        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;
            Log.v("inSampleSize",Integer.toString(inSampleSize));
        }


        return inSampleSize;
    }

    public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) {

        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;//属性设置为true就可以让解析方法禁止为bitmap分配内存,返回值也不再是一个Bitmap对象,而是null
        BitmapFactory.decodeResource(res,resId,options);
        options.inSampleSize = calculateInSampleSize(options, reqWidth,reqHeight);
        Log.v("压缩比",Integer.toString(options.inSampleSize));
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeResource(res, resId, options);
    }

}

运行效果:
图片缩小了10倍

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值