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