一:圖片OOM異常:程式碼範例:
public class MainActivity extends Activity {private ImageView iv_imageView;protected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);iv_imageView = (ImageView) findViewById(R.id.Iv_imageView);}public void load(View view){Bitmap bitmap = BitmapFactory.decodeFile("/sdcard/1.jpg");iv_imageView.setImageBitmap(bitmap);}}
出現問題:
5038848,
20155392Byte ---> 20155392/1024=19683KB ---> 19638/1024=19.2216796875MB19.2216796875MB
6.
二:對圖片進行縮放的演算法:
1.
2.
詳細代碼:
public class MainActivity extends Activity {private ImageView iv_imageView;private int windowWidth;private int windowHeight;@SuppressWarnings("deprecation")@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);iv_imageView = (ImageView) findViewById(R.id.Iv_imageView);//1.擷取手機螢幕的解析度 寬高Display display = getWindowManager().getDefaultDisplay();windowWidth = display.getWidth();windowHeight = display.getHeight();System.out.println("螢幕的寬度:" + windowHeight);System.out.println("螢幕的高度:" + windowHeight);}public void load(View view){//Bitmap bitmap = BitmapFactory.decodeFile("/sdcard/1.jpg");//iv_imageView.setImageBitmap(bitmap);Options opts = new Options(); //2.0設定解析器不去真正的解析這個位元影像,而是解析這個圖片的out輸出資訊(寬度,高度),不會為圖片的每個點申請內在空間opts.inJustDecodeBounds = true;//2.得到圖片的寬高資訊BitmapFactory.decodeFile("/sdcard/1.jpg",opts);int picHeight = opts.outHeight;int picWidth = opts.outWidth;System.out.println("圖片的寬度:" + picWidth);System.out.println("圖片的高度:" + picHeight);//3.得到縮放比例int scaleX = picWidth/windowWidth;int scaleY = picHeight/windowHeight;System.out.println("水平縮放比例:" + scaleX);System.out.println("豎直縮放比例:" + scaleY);//3.2. 確定縮放比例:int scale = 1;if(scaleX > scaleY && scaleY>1){scale = scaleX;}if(scaleY > scaleX && scaleX>1){scale = scaleY;}System.out.println("最終確定的縮放比例:" + scale);//4.真正的解析這個圖片opts.inJustDecodeBounds = false;opts.inSampleSize = scale;Bitmap bitmap = BitmapFactory.decodeFile("/sdcard/1.jpg",opts);iv_imageView.setImageBitmap(bitmap);}}
運行時log:
09-29 16:05:37.715: I/System.out(23786):
09-29 16:05:37.715: I/System.out(23786):
09-29 16:07:12.085: I/System.out(23786):
09-29 16:07:12.085: I/System.out(23786):
09-29 16:07:12.105: I/System.out(23786):
09-29 16:07:12.115: I/System.out(23786):
09-29 16:07:12.115: I/System.out(23786):
09-29 16:17:26.475: I/System.out(23786):
09-29 16:17:26.475: I/System.out(23786):
09-29 16:17:33.336: I/System.out(23786):
09-29 16:17:33.336: I/System.out(23786):
09-29 16:17:33.345: I/System.out(23786):
09-29 16:17:33.345: I/System.out(23786):
09-29 16:17:33.345: I/System.out(23786):