码迷,mamicode.com
首页 > 移动开发 > 详细

android 官网处理图片 代码

时间:2014-09-25 12:29:18      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:des   android   style   blog   color   io   ar   strong   div   

 1     /**
 2      * 获取压缩后的图片 (官网大图片加载对应代码) 
 3      * 
 4      * @param res
 5      * @param resId
 6      * @param reqWidth
 7      *            所需图片压缩尺寸最小宽度
 8      * @param reqHeight
 9      *            所需图片压缩尺寸最小高度
10      * @return
11      */
12     public static Bitmap decodeSampledBitmapFromResource(Resources res,
13             int resId, int reqWidth, int reqHeight) {
14 
15         // 首先不加载图片,仅获取图片尺寸
16         final BitmapFactory.Options options = new BitmapFactory.Options();
17         // 当inJustDecodeBounds设为true时,不会加载图片仅获取图片尺寸信息
18         options.inJustDecodeBounds = true;
19         // 此时仅会将图片信息会保存至options对象内,decode方法不会返回bitmap对象
20         BitmapFactory.decodeResource(res, resId, options);
21 
22         // 计算压缩比例,如inSampleSize=4时,图片会压缩成原图的1/4
23         options.inSampleSize = calculateInSampleSize(options, reqWidth,
24                 reqHeight);
25 
26         // 当inJustDecodeBounds设为false时,BitmapFactory.decode...就会返回图片对象了
27         options.inJustDecodeBounds = false;
28         // 利用计算的比例值获取压缩后的图片对象
29         return BitmapFactory.decodeResource(res, resId, options);
30     }
31 
32     /**
33      * 计算压缩比例值 (官网大图片加载对应代码) 
34      * 
35      * @param options
36      *            解析图片的配置信息
37      * @param reqWidth
38      *            所需图片压缩尺寸最小宽度
39      * @param reqHeight
40      *            所需图片压缩尺寸最小高度
41      * @return
42      */
43     public static int calculateInSampleSize(BitmapFactory.Options options,
44             int reqWidth, int reqHeight) {
45         // 保存图片原宽高值
46         final int height = options.outHeight;
47         final int width = options.outWidth;
48         // 初始化压缩比例为1
49         int inSampleSize = 1;
50 
51         // 当图片宽高值任何一个大于所需压缩图片宽高值时,进入循环计算系统
52         if (height > reqHeight || width > reqWidth) {
53 
54             final int halfHeight = height / 2;
55             final int halfWidth = width / 2;
56 
57             // 压缩比例值每次循环两倍增加,
58             // 直到原图宽高值的一半除以压缩值后都~大于所需宽高值为止
59             while ((halfHeight / inSampleSize) >= reqHeight
60                     && (halfWidth / inSampleSize) >= reqWidth) {
61                 inSampleSize *= 2;
62             }
63         }
64         return inSampleSize;
65     }

 

android 官网处理图片 代码

标签:des   android   style   blog   color   io   ar   strong   div   

原文地址:http://www.cnblogs.com/androidsj/p/3992367.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!