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配置

<linearlayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity">
 
    <button android:onclick="load" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="加载大图片到内存">
 
    <imageview android:id="@+id/iv" android:layout_width="match_parent" android:layout_height="match_parent">
 
</imageview></button></linearlayout>
在这种情况下,是将大分辨率的图片按照一定的比例缩小然后加载进内存,就不会出现内存溢出的现象了。

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


猜你喜欢

转载自blog.csdn.net/douzi949389/article/details/79339466