二级采样

public class MainActivity extends AppCompatActivity {

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        ImageView img1=findViewById(R.id.img1);

        ImageView img2=findViewById(R.id.img2);

 

        LruCache<String,Bitmap> cache;

 

 

        //图片的sd的路径

        String picPath = Environment.getExternalStorageDirectory().getPath() + File.separator + "bb.JPG";

 

        Bitmap bitmap = BitmapFactory.decodeFile(picPath);

        img1.setImageBitmap(bitmap);

 

 

        Bitmap compressPic = getCompressPic(picPath, 120, 120);

        img2.setImageBitmap(compressPic);

 

 

    }

 

    /**

     * 二次采样

     * @param picPath 图片的路径

     * @param expectWidth 期望的图片的宽度 (px)

     * @param expectHeight 期望的图片的高度 (px)

     * @return

     */

    public Bitmap getCompressPic(String picPath,int expectWidth,int expectHeight){

 

        //第一次采样:得到图片的实际的宽度与高度

        BitmapFactory.Options options=new BitmapFactory.Options();

        options.inJustDecodeBounds=true;//必须设置成true

 

        //转换

        BitmapFactory.decodeFile(picPath,options);

 

        //得到图片的实际宽度与高度

        int realWidth = options.outWidth;

        int realHeight = options.outHeight;

        Log.d("zzz","实际的宽度:"+realWidth+" 实际的高度:"+realHeight);

 

        /第一次采样end///

 

        //第二次采样:计算一个压缩值

        int sampleSize=1;

        if(realHeight>expectHeight || realWidth>expectWidth){

 

            int heightRate = realHeight / expectHeight;

            int widthRate = realWidth / expectWidth;

 

            //计算值  3

            sampleSize=heightRate>widthRate?heightRate:widthRate;

            Log.d("zzz","sampleSize:"+sampleSize);

 

        }

        options.inJustDecodeBounds=false;//第二次采样时设置成false

        options.inSampleSize=sampleSize;//压缩率

        options.inPreferredConfig= Bitmap.Config.RGB_565;//设置图片的色彩模式 1px=2个字节

 

        //压缩后的图片

        Bitmap bitmap = BitmapFactory.decodeFile(picPath, options);

/第二次采样end///

 

        return bitmap;

    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值