[代码片段] 【转】Android以最省内存的方式读取本地资源的

来源:互联网 发布:淘宝卖家采集器 编辑:程序博客网 时间:2024/06/05 07:48
1、获取本地图片并指定高度和宽度
?
代码片段,双击复制
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
        /**
         * 获取本地图片并指定高度和宽度
         */
        publicstatic Bitmap getNativeImage(String imagePath) {
                BitmapFactory.Options options = newBitmapFactory.Options();
                options.inJustDecodeBounds = true;
                // 获取这个图片的宽和高
                Bitmap myBitmap = BitmapFactory.decodeFile(imagePath, options); // 此时返回myBitmap为空
                // 计算缩放比
                intbe = (int) (options.outHeight / (float)200);
                intys = options.outHeight % 200;// 求余数
                floatfe = ys / (float)200;
                if(fe >= 0.5)
                        be = be + 1;
                if(be <= 0)
                        be = 1;
                options.inSampleSize = be;
 
                // 重新读入图片,注意这次要把options.inJustDecodeBounds 设为 false
                options.inJustDecodeBounds = false;
 
                myBitmap = BitmapFactory.decodeFile(imagePath, options);
                returnmyBitmap;
        }


2、以最省内存的方式读取本地资源的图片
?
代码片段,双击复制
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
        /**
         * 以最省内存的方式读取本地资源的图片
         *
         * @param context
         * @param resId
         * @return
         */
        publicstatic Bitmap readBitMap(Context context, intresId) {
                BitmapFactory.Options opt = newBitmapFactory.Options();
                opt.inPreferredConfig = Bitmap.Config.RGB_565;
                opt.inPurgeable = true;
                opt.inInputShareable = true;
                // 获取资源图片
                InputStream is = context.getResources().openRawResource(resId);
                returnBitmapFactory.decodeStream(is, null, opt);
        }


3、以最省内存的方式读取本地资源的图片 或者SDCard中的图片

?
代码片段,双击复制
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
        /**
         * 以最省内存的方式读取本地资源的图片 或者SDCard中的图片
         *
         * @param imagePath
         *            图片在SDCard中的路径
         * @return
         */
        publicstatic Bitmap getSDCardImg(String imagePath) {
                BitmapFactory.Options opt = newBitmapFactory.Options();
                opt.inPreferredConfig = Bitmap.Config.RGB_565;
                opt.inPurgeable = true;
                opt.inInputShareable = true;
                // 获取资源图片
                returnBitmapFactory.decodeFile(imagePath, opt);
        }