| /** * 圖片壓縮的方法總結 */ /* * 圖片壓縮的方法01:品質壓縮方法 */ private Bitmap compressImage(Bitmap beforBitmap) { // 可以捕獲記憶體緩衝區的資料,轉換成位元組數組。 ByteArrayOutputStream bos = new ByteArrayOutputStream(); if (beforBitmap != null) { // 第一個參數:圖片壓縮的格式;第二個參數:壓縮的比率;第三個參數:壓縮的資料存放到bos中 beforBitmap.compress(CompressFormat.JPEG, 100, bos); int options = 100; // 迴圈判斷壓縮後的圖片是否是大於100kb,如果大於,就繼續壓縮,否則就不壓縮 while (bos.toByteArray().length / 1024 > 100) { bos.reset();// 置為空白 // 壓縮options% beforBitmap.compress(CompressFormat.JPEG, options, bos); // 每次都減少10 options -= 10; } // 從bos中將資料讀出來 存放到ByteArrayInputStream中 ByteArrayInputStream bis = new ByteArrayInputStream( bos.toByteArray()); // 將資料轉換成圖片 Bitmap afterBitmap = BitmapFactory.decodeStream(bis); return afterBitmap; } return null; } /* * 圖片壓縮方法02:獲得縮圖 */ public Bitmap getThumbnail(int id) { // 獲得原圖 Bitmap beforeBitmap = BitmapFactory.decodeResource( mContext.getResources(), id); // 寬 int w = mContext.getResources() .getDimensionPixelOffset(R.dimen.image_w); // 高 int h = mContext.getResources().getDimensionPixelSize(R.dimen.image_h); // 獲得縮圖 Bitmap afterBitmap = ThumbnailUtils .extractThumbnail(beforeBitmap, w, h); return afterBitmap; } /** * 圖片壓縮03 * * @param id * 要操作的圖片的大小 * @param newWidth * 圖片指定的寬度 * @param newHeight * 圖片指定的高度 * @return */ public Bitmap compressBitmap(int id, double newWidth, double newHeight) { // 獲得原圖 Bitmap beforeBitmap = BitmapFactory.decodeResource( mContext.getResources(), id); // 圖片原有的寬度和高度 float beforeWidth = beforeBitmap.getWidth(); float beforeHeight = beforeBitmap.getHeight(); // 計算寬高縮放率 float scaleWidth = 0; float scaleHeight = 0; if (beforeWidth > beforeHeight) { scaleWidth = ((float) newWidth) / beforeWidth; scaleHeight = ((float) newHeight) / beforeHeight; } else { scaleWidth = ((float) newWidth) / beforeHeight; scaleHeight = ((float) newHeight) / beforeWidth; } // 矩陣對象 Matrix matrix = new Matrix(); // 縮放圖片動作 縮放比例 matrix.postScale(scaleWidth, scaleHeight); // 建立一個新的Bitmap 從原始映像剪下映像 Bitmap afterBitmap = Bitmap.createBitmap(beforeBitmap, 0, 0, (int) beforeWidth, (int) beforeHeight, matrix, true); return afterBitmap; } |