Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 圖片處理工具類實作:拍照、相冊、縮圖一次搞定

編輯:關於 Android 開發

為什麼需要自己封裝

Android 開放的手機市場帶來一個現實問題:各家廠商對系統的客製化程度不同,即使拍照與相冊都有基本共識,實際操作細節仍可能出現差異。作者實際測試過的機型中,就遇到過兩類典型狀況:

拍照時相機會自動旋轉一定角度(出現於部分三星機型)
相冊返回的圖片路徑藏在 URI 中(原生系統的行為)

針對這些差異,這個工具類採用兩條策略:

拍照時把圖片存到指定位置,載入時直接用檔案路徑
讀取相冊時,把返回的 URI 轉換成可用的檔案路徑

以下說明各個環節的實作,完整源碼在文末。

拍照:把結果寫進指定檔案

這裡呼叫的是系統的拍照程式,而非自行實作。好處是通用性廣,也不必處理各家硬體細節;代價是我們無法監控系統拍照程式的行為,例如前面提到的自動旋轉。因此拍照之後仍需檢測角度並修正。

建立存放圖片的檔案

路徑由外部傳入(原因後述)。檔案不存在時必須先建立,否則無法把拍照結果寫入。注意這要是完整路徑並含副檔名。

// 嘗試建立用於存放拍照結果的檔案
File outputImage = new File(filePath);
if (!outputImage.exists()) {
    try {
        outputImage.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

啟動系統相機

Action 是通用的,關鍵在於用 MediaStore.EXTRA_OUTPUT 指定輸出路徑。

Uri photoUri = Uri.fromFile(outputImage);
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);   // 指定輸出路徑
try {
    act.startActivityForResult(intent, REQUEST_CODE_TAKE_PHOTO);
} catch (SecurityException se) {
    se.printStackTrace();
    return null;
}

requestCode 使用自訂的 REQUEST_CODE_TAKE_PHOTO,因為後續會有統一的分派處理。

相冊:把 URI 還原成檔案路徑

讀取相冊同樣使用系統工具:

Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
// 若裝置有多個相冊應用,讓使用者自行選擇
act.startActivityForResult(Intent.createChooser(intent, "請選擇"),
                           REQUEST_CODE_OPEN_GRALLY);

關鍵難題:content:// 開頭的 URI

相冊返回的往往是一個 URI,但有時它並不是絕對路徑,例如:

content://media/external/images/media/45928

這串字確實指向某個資源,卻無法直接當成檔案路徑讀取。解法是透過 ContentResolver 查詢對應的資料列,取出真正的檔案路徑。

public static String getBmpPathFromContent(Context context, Intent bmpIntent) {
    if (bmpIntent != null && bmpIntent.getData() != null) {
        Uri contentUri = bmpIntent.getData();
        String uriPath = contentUri.getPath();
        if (!TextUtils.isEmpty(uriPath)) {
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            // 查詢系統媒體資料庫
            Cursor cursor = context.getContentResolver().query(
                    contentUri, filePathColumn, null, null, null);
            cursor.moveToFirst();                      // 不移動會越界
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();                            // 別忘了關閉
            return picturePath;
        }
        return null;
    }
    return null;
}

統一的分派處理

由於拍照與相冊都是以 startActivityForResult() 開啟,可以用同一個方法處理兩者的回呼:

/**
 * 處理拍照/開啟相冊後進入裁剪流程
 *
 * @param requestCode 請求碼
 * @param resultCode  結果碼
 * @param data        回傳的 Intent
 * @param act         啟動裁剪的 Activity
 * @param inputPath   拍照時指定的存放路徑(相冊的路徑在 data 中)
 * @param outputPath  裁剪後的輸出路徑
 */
public static boolean onActivityResult(int requestCode, int resultCode, Intent data,
                                       Activity act, String inputPath, String outputPath) {
    switch (requestCode) {
        case REQUEST_CODE_TAKE_PHOTO:
        case REQUEST_CODE_OPEN_GRALLY:
            // Activity 不存在或使用者取消時不處理
            if (act == null || resultCode != Activity.RESULT_OK) {
                return false;
            }

            // 拍照時才需要讀取旋轉角度
            int degree = requestCode == REQUEST_CODE_TAKE_PHOTO
                       ? readPictureDegree(inputPath) : 0;

            // 部分機型的相冊會把路徑放在 Intent 中回傳
            String tempPath = getBmpPathFromContent(act, data);
            inputPath = TextUtils.isEmpty(tempPath) ? inputPath : tempPath;

            if (TextUtils.isEmpty(inputPath) || TextUtils.isEmpty(outputPath)) {
                return false;
            }
            Intent cropIntent = new Intent(act, CropBitmapActivity.class);
            cropIntent.putExtra("inputPath", inputPath);
            cropIntent.putExtra("outputPath", outputPath);
            cropIntent.putExtra("degree", degree);
            act.startActivityForResult(cropIntent, REQUEST_CODE_CROP_PHOTO);
            return true;

        default:
            return false;
    }
}

這段邏輯中有兩處設計值得說明。

第一,onActivityResult() 在同一時間只會被回呼一次,也就是說拍照與相冊這兩條路徑不會同時成立。因此 inputPath(拍照路徑)與 tempPath(相冊路徑)最後只會保留一個:若 Intent 中取到了路徑,說明這次是相冊回呼,採用它;否則就是拍照回呼,沿用原本傳入的 inputPath。

第二,readPictureDegree() 只在拍照時呼叫,用來處理部分機型的自動旋轉問題。若你希望相冊圖片也一併校正,可以把檢測對象改成最終的 inputPath:

int degree = readPictureDegree(inputPath);

縮圖載入:省記憶體的關鍵

裁剪時通常需要載入圖片縮圖。很多情況下(例如頭像)並不需要高解析度,此時若載入一張全尺寸大圖,記憶體開銷相當可觀,在記憶體緊張時甚至可能直接 OOM 崩潰。

原理是:按比例載入較小尺寸的圖片,从而降低記憶體占用。

載入流程分為三步:

  1. 只讀取圖片的寬高資訊(不載入像素資料)
  2. 計算縮放比例
  3. 依比例載入圖片

計算 inSampleSize

BitmapFactory.Options 中的 inSampleSize 用來記錄縮放比例,取值必須大於 1;1 代表原尺寸載入,n 代表長寬各縮小為 1/n。

此外,這個值必須是 2 的 N 次方。即使你給了其他數字,BitmapFactory 也會取最接近的 2 的 N 次方(通常是向下取)。

/**
 * 計算圖片的縮放比例
 *
 * @param options 圖片資訊
 * @param reqSize 期望的圖片最長邊大小
 * @return 必定大於 0 且為 2 的 N 次方
 */
public static int calculateInSampleSize(BitmapFactory.Options options, float reqSize) {
    if (reqSize <= 0) {
        throw new RuntimeException("預期邊長不可小於 0");
    }
    float bmpWidth = options.outWidth;
    float bmpHeight = options.outHeight;
    float largeSizeInBmp = bmpWidth > bmpHeight ? bmpWidth : bmpHeight;
    int sampleSize = 1;

    if (largeSizeInBmp < reqSize) {
        sampleSize = 1;                       // 原圖已夠小,不縮放
    } else {
        sampleSize = (int) (largeSizeInBmp / reqSize + 0.5);
        // 求 log2(sampleSize),並向上取整以確保不超過指定值
        double powerNum = Math.log(sampleSize) / Math.log(2);
        int tempPowerNum = (int) powerNum;
        if (powerNum > tempPowerNum) {
            tempPowerNum += 1;
        }
        sampleSize = (int) Math.pow(2, tempPowerNum);
    }
    return sampleSize;
}

兩段式載入

縮圖載入被拆成兩個方法,這是一個實務上很重要、但文件裡沒寫的細節。

/**
 * 取得圖片載入配置
 * @param in 圖片串流,此方法執行後該串流會被關閉
 */
public static BitmapFactory.Options getStreamBitmapOptions(InputStream in, float reqSize) {
    try {
        if (in == null || reqSize <= 0) {
            return null;
        }
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;              // 只讀資訊
        BitmapFactory.decodeStream(in, null, options);

        int sampleSize = calculateInSampleSize(options, reqSize);

        options.inJustDecodeBounds = false;             // 改為正式載入
        options.inSampleSize = sampleSize;
        return options;
    } finally {
        if (in != null) {
            try { in.close(); } catch (IOException e) { e.printStackTrace(); }
        }
    }
}

/**
 * 依配置載入縮圖
 * @param in 圖片串流,建議重新開啟(不要使用讀過資訊的那個串流)
 */
public static Bitmap decodeBitmapInScale(InputStream in, BitmapFactory.Options options) {
    try {
        if (in == null || options == null || in.available() <= 0) {
            return null;
        }
        return BitmapFactory.decodeStream(in, null, options);
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    } finally {
        if (in != null) {
            try { in.close(); } catch (IOException e) { e.printStackTrace(); }
        }
    }
}

為什麼要拆成兩段、而且必須用兩個全新的串流?這是實測得到的結論:用同一個 InputStream 先讀取配置資訊、再拿去載入圖片,很可能會載入失敗。

查閱源碼可以確認,BitmapFactory.decodeFile() 與 decodeResource() 之所以不受影響,是因為它們內部本來就會重新開啟串流。

因此,讀取配置與載入圖片時,必須使用同一個檔案的兩個全新串流物件,不能複用同一個。

基於同樣的理由,也提供了針對路徑與資源的便捷版本:

public static Bitmap decodeBitmapInScale(String filePath, int reqSize) {
    InputStream in = getBmpInputStream(filePath);
    BitmapFactory.Options options = getStreamBitmapOptions(in, reqSize);
    in = getBmpInputStream(filePath);          // 重新開啟一個串流
    return decodeBitmapInScale(in, options);
}

public static Bitmap decodeBitmapInScale(Resources res, int resID, int reqSize) {
    InputStream in = getBmpInputStream(res, resID);
    BitmapFactory.Options options = getStreamBitmapOptions(in, reqSize);
    in = getBmpInputStream(res, resID);        // 重新開啟一個串流
    return decodeBitmapInScale(in, options);
}

實際效果

I/bmp: sampleSize = 4          // 長寬縮小為 1/4,面積縮小為 1/16
       srcWidth = 1152
       srcHeight = 1920

I/bmp: scaleWidth = 288
       scaleHeight = 480

以 ARGB_8888 格式計算,每個像素占 4 個位元組:

  • 原圖:1152 × 1920 × 4 / 1024 / 1024 ≈ 8 MB
  • 縮圖:288 × 480 × 4 / 1024 / 1024 ≈ 0.5 MB

所以在可以用縮圖的場合,盡量用縮圖,別讓一張大圖壓垮記憶體。

另外,存檔時若非 PNG 格式,可以透過降低 quality 參數來縮小檔案(PNG 為無損壓縮,此參數無效)。

完整源碼

以下包含圖片旋轉、縮圖載入、拍照/相冊呼叫,以及自訂裁剪 Activity 的啟動。

public class GrallyAndPhotoUtils {

    public static final int REQUEST_CODE_TAKE_PHOTO = 0x1;   // 拍照
    public static final int REQUEST_CODE_OPEN_GRALLY = 0x2;  // 相冊
    public static final int REQUEST_CODE_CROP_PHOTO = 0x3;   // 裁剪

    /** 依路徑載入縮圖 */
    public static Bitmap decodeBitmapInScale(String filePath, int reqSize) {
        InputStream in = getBmpInputStream(filePath);
        BitmapFactory.Options options = getStreamBitmapOptions(in, reqSize);
        in = getBmpInputStream(filePath);
        return decodeBitmapInScale(in, options);
    }

    /** 依資源載入縮圖 */
    public static Bitmap decodeBitmapInScale(Resources res, int resID, int reqSize) {
        InputStream in = getBmpInputStream(res, resID);
        BitmapFactory.Options options = getStreamBitmapOptions(in, reqSize);
        in = getBmpInputStream(res, resID);
        return decodeBitmapInScale(in, options);
    }

    /** 取得圖片載入配置 */
    public static BitmapFactory.Options getStreamBitmapOptions(InputStream in, float reqSize) {
        try {
            if (in == null || reqSize <= 0) {
                return null;
            }
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(in, null, options);
            options.inJustDecodeBounds = false;
            options.inSampleSize = calculateInSampleSize(options, reqSize);
            return options;
        } finally {
            closeQuietly(in);
        }
    }

    /** 依配置載入縮圖 */
    public static Bitmap decodeBitmapInScale(InputStream in, BitmapFactory.Options options) {
        try {
            if (in == null || options == null || in.available() <= 0) {
                return null;
            }
            Log.i("bmp", "sampleSize = " + options.inSampleSize
                        + "\nsrcWidth = " + options.outWidth
                        + "\nsrcHeight = " + options.outHeight);
            return BitmapFactory.decodeStream(in, null, options);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            closeQuietly(in);
        }
    }

    /** 計算縮放比例,結果必為 2 的 N 次方 */
    public static int calculateInSampleSize(BitmapFactory.Options options, float reqSize) {
        if (reqSize <= 0) {
            throw new RuntimeException("預期邊長不可小於 0");
        }
        float largeSizeInBmp = Math.max(options.outWidth, options.outHeight);
        if (largeSizeInBmp < reqSize) {
            return 1;
        }
        int sampleSize = (int) (largeSizeInBmp / reqSize + 0.5);
        double powerNum = Math.log(sampleSize) / Math.log(2);
        int tempPowerNum = (int) powerNum;
        if (powerNum > tempPowerNum) {
            tempPowerNum += 1;
        }
        return (int) Math.pow(2, tempPowerNum);
    }

    /** 從路徑開啟串流,失敗回傳 null */
    public static InputStream getBmpInputStream(String filePath) {
        try {
            return new FileInputStream(new File(filePath));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /** 從資源開啟串流,失敗回傳 null */
    public static InputStream getBmpInputStream(Resources res, int resID) {
        if (res == null || resID == 0) {
            return null;
        }
        return res.openRawResource(resID);
    }

    /** 讀取圖片的 EXIF 旋轉角度 */
    public 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 (Exception e) {
            e.printStackTrace();
        }
        return degree;
    }

    /** 旋轉圖片 */
    public static Bitmap rotatingBitmap(int angle, Bitmap bitmap) {
        if (bitmap == null || bitmap.isRecycled()) {
            return null;
        }
        Matrix matrix = new Matrix();
        matrix.postRotate(angle);
        return Bitmap.createBitmap(bitmap, 0, 0,
                bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    }

    /** 儲存圖片到檔案 */
    public boolean saveBitmapToFile(String outputPath, Bitmap bitmap,
                                    Bitmap.CompressFormat format, int quality) {
        if (bitmap == null || TextUtils.isEmpty(outputPath)) {
            return false;
        }
        if (quality < 0 || quality > 100) {
            quality = 50;
        }
        try {
            File file = new File(outputPath);
            if (!file.exists()) {
                file.createNewFile();
            }
            FileOutputStream out = new FileOutputStream(file);
            bitmap.compress(format, quality, out);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    /** 把 content URI 轉成真正的檔案路徑 */
    public static String getBmpPathFromContent(Context context, Intent bmpIntent) {
        if (bmpIntent == null || bmpIntent.getData() == null) {
            return null;
        }
        Uri contentUri = bmpIntent.getData();
        if (TextUtils.isEmpty(contentUri.getPath())) {
            return null;
        }
        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor cursor = context.getContentResolver().query(
                contentUri, filePathColumn, null, null, null);
        if (cursor == null) {
            return null;
        }
        try {
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            return cursor.getString(columnIndex);
        } finally {
            cursor.close();
        }
    }

    /** 開啟相機拍照 */
    public static Uri openCamera(Activity act, String filePath) {
        if (TextUtils.isEmpty(filePath)) {
            throw new RuntimeException("filePath can not be null");
        }
        File outputImage = new File(filePath);
        if (!outputImage.exists()) {
            try {
                outputImage.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
        }
        Uri photoUri = Uri.fromFile(outputImage);
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
        try {
            act.startActivityForResult(intent, REQUEST_CODE_TAKE_PHOTO);
        } catch (SecurityException se) {
            se.printStackTrace();
            return null;
        }
        return photoUri;
    }

    /** 開啟相冊 */
    public static void openGrally(Activity act) {
        if (act == null) {
            return;
        }
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        act.startActivityForResult(Intent.createChooser(intent, "請選擇"),
                                   REQUEST_CODE_OPEN_GRALLY);
    }

    /** 統一處理拍照/相冊回呼 */
    public static boolean onActivityResult(int requestCode, int resultCode, Intent data,
                                           Activity act, String inputPath, String outputPath) {
        switch (requestCode) {
            case REQUEST_CODE_TAKE_PHOTO:
            case REQUEST_CODE_OPEN_GRALLY:
                if (act == null || resultCode != Activity.RESULT_OK) {
                    return false;
                }
                int degree = requestCode == REQUEST_CODE_TAKE_PHOTO
                           ? readPictureDegree(inputPath) : 0;
                String tempPath = getBmpPathFromContent(act, data);
                inputPath = TextUtils.isEmpty(tempPath) ? inputPath : tempPath;
                if (TextUtils.isEmpty(inputPath) || TextUtils.isEmpty(outputPath)) {
                    return false;
                }
                Intent cropIntent = new Intent(act, CropBitmapActivity.class);
                cropIntent.putExtra("inputPath", inputPath);
                cropIntent.putExtra("outputPath", outputPath);
                cropIntent.putExtra("degree", degree);
                act.startActivityForResult(cropIntent, REQUEST_CODE_CROP_PHOTO);
                return true;
            default:
                return false;
        }
    }

    private static void closeQuietly(InputStream in) {
        if (in != null) {
            try { in.close(); } catch (IOException e) { e.printStackTrace(); }
        }
    }
}

示例

這個工具類可以用來開啟相冊或相機,以下示範相冊選圖後進入裁剪的流程。工具類本身只負責圖片處理,不包含裁剪實作,裁剪部分另見 CropView 與 CropBitmapActivity 的相關說明。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved