
/** * 讀取圖片屬性:旋轉的角度 * @param path 圖片絕對路徑 * @return degree旋轉的角度 */ public int readPictureDegree(String path) { int degree = 0; try { ExifInterface exifInterface = new ExifInterface(path); int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); switch (orientation) { case ExifInterface.ORIENTATION_ROTATE_90: degree = 90; break; case ExifInterface.ORIENTATION_ROTATE_180: degree = 180; break; case ExifInterface.ORIENTATION_ROTATE_270: degree = 270; break; } } catch (IOException e) { e.printStackTrace(); } return degree; } /* * 旋轉圖片 * @param angle * @param bitmap * @return Bitmap */ public Bitmap rotaingImageView(int angle , Bitmap bitmap) { //旋轉圖片 動作 Matrix matrix = new Matrix(); matrix.postRotate(angle); // 創建新的圖片 return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); } /*** * 將bitmap保存在SD jpeg格式 * * @param bitmap * 圖片bitmap * @param filePath * 要保存圖片路徑 * @param quality * 壓縮質量值 */ public void saveImage(Bitmap bitmap, String filePath, int quality) { FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(filePath); bitmap.compress(CompressFormat.JPEG, quality, fileOutputStream); fileOutputStream.flush(); fileOutputStream.close(); // 如果圖片還沒有回收,強制回收 if (!bitmap.isRecycled()) { bitmap.recycle(); System.gc(); } } catch (Exception e) { } } bitmap=ImageCompress.decodeSampledBitmapFromResource(filename, 480, 800); //圖片旋轉 int Degree = imageUtils.readPictureDegree(filename); bitmap = imageUtils.rotaingImageView(Degree, bitmap); //保存圖片到SD卡 //imageCompress.saveImage(bitmap, filename); imageCompress.saveImage(bitmap, filename,90);

/*** * 動態設置inSampleSize 倍數 * * @param pathName * 圖片路徑 * @param reqWidth * 要壓縮的寬度 * @param reqHeight * 要壓縮的高度 * @return */ public static Bitmap decodeSampledBitmapFromResource(String pathName, int reqWidth, int reqHeight) { // 首先設置 inJustDecodeBounds=true 來獲取圖片尺寸 final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(pathName, options); // 計算 inSampleSize 的值 options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // 根據計算出的 inSampleSize 來解碼圖片生成Bitmap options.inJustDecodeBounds = false; return BitmapFactory.decodeFile(pathName, options); }