Android -- 加载大图片的方法
时间:2014-05-28 16:23:10
收藏:0
阅读:295
在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); } }
在这种情况下,是将大分辨率的图片按照一定的比例缩小然后加载进内存,就不会出现内存溢出的现象了。
转载请注明出处:http://www.cnblogs.com/yydcdut/p/3744876.html
评论(0)