解决 out of memory 的方法

本文介绍了一种使用BitmapFactory.Options来实现图片压缩和缩放的方法。通过调整inSampleSize参数来减少图片尺寸,同时保持图片质量,适用于Android应用中加载大尺寸图片的需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

private Bitmap decodeBitmap(File file){
        try{
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(file),null,o);
            Bitmap currentBitmap = Bitmap.createBitmap(o.outWidth,o.outHeight, Bitmap.Config.ARGB_8888);

            final int REQYIRED_SIZE  = 800;
            int scale = 1;
            while (o.outWidth / 2 / scale >= REQYIRED_SIZE && o.outHeight / 2 /scale >= REQYIRED_SIZE){
                scale *= 2;
            }
            //Log.e(TAG, "decodeBitmap: scale---"+scale);
            o.inJustDecodeBounds = false;
            o.inSampleSize = scale;
            o.inMutable = true;
            o.inBitmap = currentBitmap;
            return BitmapFactory.decodeStream(new FileInputStream(file),null,o);
            //return currentBitmap;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }