Android中圖片的縮放

來源:互聯網
上載者:User

在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);

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.