Android加載大圖片到內存
在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); } } </pre><br />
xml文件
<LinearLayout xmlns:android=" xmlns: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> </pre><br />
在這種情況下,是將大分辨率的圖片按照一定的比例縮小然后加載進內存,就不會出現內存溢出的現象了。
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!