bitmapFactory压缩本地图片

来源:互联网 发布:淘宝客服工作内容介绍 编辑:程序博客网 时间:2024/06/10 08:45

–由于G20没地方完去了, 所以在这里写写博客,不写博客的程序员不是好裁缝!很多人会遇到这样的问题,不知道图片如何压缩之后再适配到android中的组件,如imageview等,因为android中产生的oom基本都是图片曹操的,因为系统分配给每个app的内存都是有限而且一定的,所以图片如何处理显得格外重要思密达!!!下来我们就开始撸代码了!*
想要改变图片的大小,基本都是改变bitmapFactory.options的inSampleSize的值, 假如这个是1, 则 图片会被压缩为原图的宽高的1/1(有没有晕, 还这么写), 如果是2, 则是原图的宽高的1/2, 这样图片就变小了, 所以我们的任务很简单, 就是改变inSampleSize, ok, 代码奉上!!!**

 public static Bitmap getRightBitmap(String filePath, int reqWidth, int reqHeight) {        BitmapFactory.Options options = new BitmapFactory.Options();        //似不似只获取原图的宽高,当然是true了;        options.inJustDecodeBounds = true;    //获取        BitmapFactory.decodeFile(filePath,options);    //获取改变后的值,并赋值给现在的inSampleSize        options.inSampleSize = calculte(options, reqWidth, reqHeight);    //搞完事,擦屁股,有该为false,获取整个位图        options.inJustDecodeBounds = false;    //返回压缩后的bitmap        return BitmapFactory.decodeFile(filePath, options);    }    /**     * get right inSampleSize     * @param options BitmapFactory     * @param reqWidth the height wo need     * @param reqHeight the widht wo need     * @return int inSampleSize  wo need     */    private static int calculte(BitmapFactory.Optionsoptions, int reqWidth, int reqHeight) {        int outHeight = options.outHeight;        int outWidth = options.outWidth;        int inSampleSize = 1;    if (reqWidth > outHeight || reqHeight > outHeight) {            int widthRate = Math.round(reqWidth * 1.0f / outWidth);//round四舍五入,因为inSampleSize必须是int类型            int heightRate = Math.round(reqHeight * 1.0f / outHeight);        //获取2个值中的最大值,压缩图片当然是要按大的值压缩,记住这里是倒数            inSampleSize = Math.max(widthRate, heightRate);        }        return inSampleSize;    }多来一嘴,小的初来乍到,macDown不怎么6,观众老爷先难受难受!!!
0 0
原创粉丝点击