Android中 加载一张大图片Caused by: java.lang.OutOfMemoryError

Bitmap bitmap= BitmapFactory.decodeFile("/sdcard/a.jpg");
    iv.setImageBitmap(bitmap);

在android中要加载一张大图片到内存中,会抛出内存溢出异常Caused by: java.lang.OutOfMemoryError。

正确的做法应该是这样的:

public class MainActivity extends Activity {
    private ImageView iv;
    private int windowHeight;
    private int windowWidth;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        iv = (ImageView) findViewById(R.id.iv);
        WindowManager win = (WindowManager) getSystemService(WINDOW_SERVICE);
        windowHeight = win.getDefaultDisplay().getHeight();
        windowWidth = win.getDefaultDisplay().getWidth();
    }
 
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
 
    public void load(View view) {
         
    /*   Bitmap bitmap= BitmapFactory.decodeFile("/sdcard/a.jpg");
         iv.setImageBitmap(bitmap);*/
          
        // 图片解析的配置
        BitmapFactory.Options options = new Options();
        // 不去真的解析图片,只是获取图片的头部信息宽,高
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile("/sdcard/a.jpg", options);
        int imageHeight = options.outHeight;
        int imageWidth = options.outWidth;
        // 计算缩放比例
        int scaleX = imageWidth / windowWidth;
        int scaleY = imageHeight / windowHeight;
        int scale = 1;
        if (scaleX > scaleY & scaleY >= 1) {
            scale = scaleX;
 
        }else if (scaleY > scaleX & scaleX >= 1) {
            scale = scaleY;
 
        }
        //真的解析图片
        options.inJustDecodeBounds=false;
        //设置采样率
        options.inSampleSize=scale;
        Bitmap bitmap=BitmapFactory.decodeFile("/sdcard/a.jpg", options);
        iv.setImageBitmap(bitmap);
    }
 
}

xml配置


 
    
在这种情况下,是将大分辨率的图片按照一定的比例缩小然后加载进内存,就不会出现内存溢出的现象了。

转自: https://www.2cto.com/kf/201404/293670.html


你可能感兴趣的:(JavaSE,Android)