在Android中,匯入的圖片尺寸太大,或者是圖片體積過大,都會導致out of memory錯誤
解決的方法有很多種,其中比較簡單的一種是預先讀入映像的檔案頭,得到映像的尺寸大小,然後將他的尺寸和期望的尺寸進行對比,得到縮放係數,設定option參數,然後用該參數讀取輸入的映像,那麼得到的映像就是縮小後的映像
具體代碼如下:
BitmapFactory.Options opt = new BitmapFactory.Options();// only read the header of file, not data 唯讀取檔案頭opt.inJustDecodeBounds = true; Bitmap bitmap = BitmapFactory.decodeFile(image_path, opt);// 得到圖片的尺寸int picWidth = opt.outHeight;int picHeight = opt.outHeight;int screenWidth;int screenHeight;if (false) {//acquire the height and width of window WindowManager winManager = getWindowManager(); Display display = winManager.getDefaultDisplay(); screenWidth = display.getWidth(); screenHeight = display.getHeight(); } else { //或者是設定指定的寬高screenWidth = 800;screenHeight = 600;}opt.inSampleSize = 1;if (picWidth > picHeight) {if (picWidth > screenWidth) opt.inSampleSize = picWidth/screenWidth;} else {if (picHeight > screenHeight)opt.inSampleSize = picHeight/screenHeight;}// 設定好縮放係數opt後,重新讀取映像opt.inJustDecodeBounds = false;bitmap = BitmapFactory.decodeFile(image_path, opt);