您的位置:首页 > 移动开发 > Android开发

Android 图片加载,内存过大问题

2016-08-31 16:02 176 查看
问题描述:

本人要实现Android本地图片加载,并实现轮播效果。代码调试过程中真心被内存问题搞得想说爱你不容易。最后查阅资料,得到以下方案,内存问题得到有效改善,希望对各位有用。

解决方案:(封好的方法,直接调用即可)

public Bitmap decodeBitmap(String path)

    {

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

        options.inJustDecodeBounds = true;

        //把它设为true,那么BitmapFactory.decodeFile(String path, Options opt)

        //并不会真的返回一个Bitmap给你,

        //它仅仅会把它的宽,高取回来给你,这样就不会占用太多的内存,也就不会那么频繁的发生OOM了

        

        // 通过这个bitmap获取图片的宽和高       

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

        

        if (bitmap == null)

        {

             System.out.println("bitmap为空");

        }

        

        float realWidth = options.outWidth;

        float realHeight = options.outHeight;

        System.out.println("真实图片高度:" + realHeight + "宽度:" + realWidth);

        // 计算缩放比       

        int scale = (int) ((realHeight > realWidth ? realHeight : realWidth) / 100);

        if (scale <= 0)

        {

            scale = 1;

        }

        options.inSampleSize = scale;

        options.inJustDecodeBounds = false;

        options.inPreferredConfig = Config.RGB_565;

        options.inDither = true;

          // 注意这次要把options.inJustDecodeBounds 设为 false,这次图片是要读取出来的。

          //      

        bitmap = BitmapFactory.decodeFile(path, options);

       

        return bitmap;

    }   

代码主体:

String picPath=Environment.getExternalStorageDirectory().getAbsolutePath()+ "/SouthElectric"+deviceId+"/"+nList.get(i);

                        Bitmap bm =decodeBitmap(picPath);

就这么多啦,图片加载内存问题是绕不过去的坎。鉴于本人能力有限,只能优化到这里了,如果各位兄台还有更好的解决方案,可以交流撒~有用的话点个赞哟!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息