Android在小内存手机(运存2G)加载图片Java.lang.OutOfMemeoryError

问题的发现

测试给提了个bug :选择图片上传APP闪退。我随手拿起手机测试,并未复现,随即拿上测试用的机型,依然没有,找测试——》又出现了——》我说你给我操作一次,然后一调试发现是Java.lang.OutOfMemeoryError异常,还是gradle引入的库里面的,换框架成本太高,算了,调试一把,定位问题以后,发现是这行代码报错
报错的代码随后使用Profiler查看内存,超过128M的时候就报错了,后来测试了半天,发现只有在运行内存2个G的手机上有问题,既然发现了问题,那就针对这个做下改动

问题解决

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

    

float maxMemory = (float) (Runtime.getRuntime().maxMemory() * 1.0/ (1024 * 1024));

    Log.d("compress","maxMemory-------------------------"+maxMemory);
    if(maxMemory <= 128){//针对内存小的手机进行了优化
        options.inSampleSize = computeSize() <= 1 ? computeSize() : computeSize() + 2;
    }else {
        options.inSampleSize = computeSize();
    }


    Bitmap tagBitmap = BitmapFactory.decodeFile(srcImg, options);
    ByteArrayOutputStream stream = new ByteArrayOutputStream();

    tagBitmap = rotatingImage(tagBitmap);
    tagBitmap.compress(Bitmap.CompressFormat.JPEG, 90, stream);
    tagBitmap.recycle();

    FileOutputStream fos = new FileOutputStream(tagImg);
    fos.write(stream.toByteArray());
    fos.flush();
    fos.close();
    stream.close();


private int computeSize() {
        srcWidth = srcWidth % 2 == 1 ? srcWidth + 1 : srcWidth;
        srcHeight = srcHeight % 2 == 1 ? srcHeight + 1 : srcHeight;

        int longSide = Math.max(srcWidth, srcHeight);
        int shortSide = Math.min(srcWidth, srcHeight);

        float scale = ((float) shortSide / longSide);
        if (scale <= 1 && scale > 0.5625) {
            if (longSide < 1664) {
                return 1;
            } else if (longSide >= 1664 && longSide < 4990) {
                return 2;
            } else if (longSide > 4990 && longSide < 10240) {
                return 4;
            } else {
                return longSide / 1280 == 0 ? 1 : longSide / 1280;
            }
        } else if (scale <= 0.5625 && scale > 0.5) {
            return longSide / 1280 == 0 ? 1 : longSide / 1280;
        } else {
            return (int) Math.ceil(longSide / (1280.0 / scale));
        }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值