Android圖片壓縮尺寸及品質

來源:互聯網
上載者:User

在Android開發中為了防止記憶體溢出,在顯示圖片時通常都對圖片進行不同的壓縮,以下就是壓縮的代碼:

第一步:先通過對圖片大小及手機螢幕尺寸的計算得出來的值然後對圖片的尺寸進行縮小,在這時尺寸壓縮後,

             在產生Bitmap時就不會出現OutOfMemoryException異常了。尺寸壓縮使用Options的inSampleSize屬性

             來控制縮放比例。

第二步:壓縮圖片品質,根據檔案大小來判斷壓縮程度。

public Bitmap createNewBitmapAndCompressByFile(String filePath, int wh[]) {int offset = 100;File file = new File(filePath);long fileSize = file.length();if (200 * 1024 < fileSize && fileSize <= 1024 * 1024)offset = 90;else if (1024 * 1024 < fileSize)offset = 85;BitmapFactory.Options options = new BitmapFactory.Options();options.inJustDecodeBounds = true; // 為true裡唯讀圖片的資訊,如果長寬,返回的bitmap為nulloptions.inPreferredConfig = Bitmap.Config.ARGB_8888;options.inDither = false;/** * 計算圖片尺寸 //TODO 按比例縮放尺寸 */BitmapFactory.decodeFile(filePath, options);int bmpheight = options.outHeight;int bmpWidth = options.outWidth;int inSampleSize = bmpheight / wh[1] > bmpWidth / wh[0] ? bmpheight / wh[1] : bmpWidth / wh[0];// if(bmpheight / wh[1] < bmpWidth / wh[0]) inSampleSize = inSampleSize * 2 / 3;//TODO 如果圖片太寬而高度太小,則壓縮比例太大。所以乘以2/3if (inSampleSize > 1)options.inSampleSize = inSampleSize;// 設定縮放比例options.inJustDecodeBounds = false;InputStream is = null;try {is = new FileInputStream(file);} catch (FileNotFoundException e) {return null;}Bitmap bitmap = null;try {bitmap = BitmapFactory.decodeStream(is, null, options);} catch (OutOfMemoryError e) {System.gc();bitmap = null;}if (offset == 100)return bitmap;// 縮小品質ByteArrayOutputStream baos = new ByteArrayOutputStream();bitmap.compress(Bitmap.CompressFormat.JPEG, offset, baos);byte[] buffer = baos.toByteArray();options = null;if (buffer.length >= fileSize)return bitmap;return BitmapFactory.decodeByteArray(buffer, 0, buffer.length);}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.