android的照相功能隨着手機硬件的發展,變得愈來愈強大,可以找出很高分辨率的圖片。
有些場景中,須要照相而且上傳到服務,可是因爲圖片的大小太大,那麼就上傳就會很慢(在有些網絡狀況下),並且很耗流量,要想速度快,那麼就須要減少圖片的大小。減小圖片的大小有兩種方法,1. 照小圖片; 2. 壓縮大圖片。 照相時獲取小圖片通常不太符合要求,由於,圖片的清晰度會不好,可是這種狀況有個好處就是應用速度會快些; 壓縮圖片,就是把大圖片壓縮小,下降圖片的質量,在必定範圍內,下降圖片的大小,而且知足需求(圖片仍就清晰)。下面組要是介紹圖片的壓縮:
2. 壓縮過程:
2.1 從圖片路徑中讀取圖片(圖片很大,不能所有加在到內存中處理,要是所有加載到內存中會內存溢出)
- final BitmapFactory.Options options = new BitmapFactory.Options();
- options.inJustDecodeBounds = true;
- BitmapFactory.decodeFile(filePath, options);
-
-
- options.inSampleSize = calculateInSampleSize(options, 480, 800);
-
-
- options.inJustDecodeBounds = false;
-
- Bitmap bm = BitmapFactory.decodeFile(filePath, options);
2.2 處理圖片旋轉
- int degree = readPictureDegree(filePath);
- bm = rotateBitmap(bm,degree) ;
- private static 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;
- }
- private static Bitmap rotateBitmap(Bitmap bitmap, int rotate){
- if(bitmap == null)
- return null ;
-
- int w = bitmap.getWidth();
- int h = bitmap.getHeight();
-
-
- Matrix mtx = new Matrix();
- mtx.postRotate(rotate);
- return Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true);
- }
2.3壓縮圖片
- bm.compress(Bitmap.CompressFormat.JPEG, 30, baos);
完整的方法代碼:
- public static Bitmap getSmallBitmap(String filePath) {
-
- final BitmapFactory.Options options = new BitmapFactory.Options();
- options.inJustDecodeBounds = true;
- BitmapFactory.decodeFile(filePath, options);
-
-
- options.inSampleSize = calculateInSampleSize(options, 480, 800);
-
-
- options.inJustDecodeBounds = false;
-
- Bitmap bm = BitmapFactory.decodeFile(filePath, options);
- if(bm == null){
- return null;
- }
- int degree = readPictureDegree(filePath);
- bm = rotateBitmap(bm,degree) ;
- ByteArrayOutputStream baos = null ;
- try{
- baos = new ByteArrayOutputStream();
- bm.compress(Bitmap.CompressFormat.JPEG, 30, baos);
-
- }finally{
- try {
- if(baos != null)
- baos.close() ;
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return bm ;
-
- }
- private static int calculateInSampleSize(BitmapFactory.Options options,
- int reqWidth, int reqHeight) {
-
- final int height = options.outHeight;
- final int width = options.outWidth;
- int inSampleSize = 1;
-
- if (height > reqHeight || width > reqWidth) {
-
-
-
- final int heightRatio = Math.round((float) height
- / (float) reqHeight);
- final int widthRatio = Math.round((float) width / (float) reqWidth);
-
-
-
-
-
- inSampleSize = heightRatio < widthRatio ? widthRatio : heightRatio;
- }
-
- return inSampleSize;
- }