Android加载大图片到内存
jopen
9年前
在android中要加载一张大图片到内存中如果通过如下方式进行
Bitmap bitmap= BitmapFactory.decodeFile("/sdcard/a.jpg"); iv.setImageBitmap(bitmap);
则会抛出内存溢出异常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="http://schemas.android.com/apk/res/android" xmlns:tools="http://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" /> </LinearLayout>
在这种情况下,是将大分辨率的图片按照一定的比例缩小然后加载进内存,就不会出现内存溢出的现象了。