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

Android 實用工具類:GalleryAndPhotoUtils 圖片處理利器

編輯:關於 Android 程式設計

概述

此工具類封裝了系統拍照與開啟相簿選圖的簡便呼叫方式,並針對多種機型做了相容性處理(實測魅族 MX4、三星 Note 2、三星 Note 3 皆正常)。


前言

由於 Android 開放的特性,各家手機廠商往往會客製自己的系統,因此即使拍照或開啟相簿多半有基本標準,不同系統的操作方式或細節仍可能存在差異。實務上常見的狀況包括:

拍照時相機會自動旋轉一定角度(常見於三星機型)
相簿圖片返回的路徑存放於 URI 中(原生系統)

為了在各種情況下都能正確取得圖片,本工具類採用的策略是:

拍照時將圖片保存到指定位置,載入時透過圖片路徑讀取
取得相簿圖片時,透過返回的 URI 解析出圖片路徑再載入


拍照

此處呼叫的是系統的拍照程式,而非自行實作,相容性更廣,也省去自行處理各種機型差異的時間。不過,系統拍照程式無法由我們監控,部分機型可能會自動旋轉相片角度,因此拍照後取得圖片時,宜先偵測是否存在旋轉角度並加以修正。


建立儲存拍照圖片的檔案

儲存路徑由外部提供。先檢測該路徑下的檔案是否存在,若不存在則建立一個新的空檔案——因為檔案不存在時,將無法把拍照結果寫入。此路徑應為含圖片格式副檔名的完整路徑。

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

呼叫系統拍照程式

呼叫系統拍照程式的 Action 是通用的,需特別注意的是設定拍照參數,將圖片輸出到指定路徑。

// 將 File 物件轉為 Uri 並啟動照相程式
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,以便後續統一處理。


讀取相簿圖片

讀取相簿圖片同樣使用系統的相簿工具。

// 設置選擇 Action
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
act.startActivityForResult(Intent.createChooser(intent, "請選擇"), REQUEST_CODE_OPEN_GRALLY);

解析返回 URI 中的圖片路徑

相簿開啟圖片後,返回的往往是一個 URI,存放圖片路徑,但未必是绝对路徑。例如可能返回如下的 URI:

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

這並非檔案的絕對路徑,無法直接讀取,但它確實指向某個資源檔。因此需將此 URI 轉換為可讀取的圖片路徑:

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;
        } else {
            return null;
        }
    } else {
        return null;
    }
}

透過 ContentResolver 查詢該 URI 對應的圖片資訊,即可取得可直接讀取的圖片路徑。


統一的回呼處理

無論拍照或開啟相簿,都是透過 startActivityForResult() 開啟並取得資料,因此可用統一方式處理兩者的回呼。

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;
            } else {
                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() 僅會回呼一次,也就是說任何時候只會處理拍照或相簿中的一種情況。其中 int degree = ... 一行用以處理拍照後圖片的旋轉角度問題;getBmpPathFromContent 則用於解析相簿圖片路徑。inputPath 僅為拍照圖片的儲存路徑,與相簿無關,因此最終只會保留其中一個。最後呼叫自訂的裁剪 CropBitmapActivity 進行裁剪(裁剪細節請參閱相關文章)。


圖片縮圖載入

裁剪圖片時常需載入縮圖。由於多數情況(如頭像等小圖)並不需要高清晰度,若直接載入高清大圖將佔用可觀記憶體,記憶體吃緊時甚至會導致崩潰。縮圖載入的原理是:

按比例載入更小比例的圖片,从而降低記憶體佔用。

BitmapFactory 本身即可指定比例載入圖片,但只能載入縮圖,無法放大超過原圖比例。

載入流程

載入圖片的寬高(僅讀取圖片資訊,不載入圖片資料)→ 計算縮圖比例 → 按縮圖比例載入圖片。

計算縮圖比例

在 BitmapFactory.Options 中,inSampleSize 變數用於記錄載入圖片與原圖的比例。此值須大於 1,1 表示按原圖比例載入,大於 1 表示長寬縮小為 1/inSampleSize 載入。此外,該值必須為 2 的 N 次方,若給定值並非 2 的 N 次方,BitmapFactory 會取最接近的 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 = 0;
    int sampleSize = 1;
    if (bmpWidth > bmpHeight) {
        largeSizeInBmp = bmpWidth;
    } else {
        largeSizeInBmp = bmpHeight;
    }
    if (largeSizeInBmp < reqSize) {
        sampleSize = 1;
    } else {
        sampleSize = (int) (largeSizeInBmp / reqSize + 0.5);
        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;
}

縮圖載入

縮圖可從圖片資料流、資源或路徑載入,但本質上都是透過資料流載入。以下提供針對資料流的載入方法:

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

圖片載入分為兩部分:一部分讀取圖片資訊並計算縮圖比例,回傳配置物件 BitmapFactory.Options;另一部分則依新的縮圖配置載入縮圖物件。之所以分兩次,是因為:

當使用同一個資料流 in 載入出配置資訊後,再重複使用該流載入圖片,很可能會載入失敗。

此問題經實測確認。當使用 BitmapFactory.decodeFile() 與 decodeResource() 時皆可正常載入,但使用 decodeStream() 並重用同一個流時便會失敗。查閱原始碼可知,decodeFile() 與 decodeResource() 實際上也是先將檔案與資源載入成流再載入圖片。因此,載入配置資訊與載入圖片時,需使用同一個檔案的兩個全新資料流物件,而非重用同一個流。

類似地,也提供了針對路徑與資源的載入方法:

public static Bitmap decodeBitmapInScale(String filePath, int reqSize) {
    InputStream in = null;
    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 = null;
    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

可見全圖縮小為原來的 1/16,長寬由 1152×1920 縮小為 288×480。以 ARGB.8888 格式計算,每個像素使用 4 個位元組:原圖約佔 8M(1152×1920×4/1024/1024),縮小後僅約 0.5M(288×480×4/1024/1024)。

因此,在可使用縮圖的情況下,應盡量使用縮圖,以免加重程式的記憶體負擔。而保存圖片時,若非 PNG 格式,也可降低保存品質以縮小檔案(多用於 JPG)。


示例

此工具類可開啟相簿與相機,此處僅示例相簿開啟並裁剪圖片。本工具類不含裁剪功能,僅提供圖片處理方法,詳細裁剪實作請參考 CropView 及 CropBitmapActivity 相關文章。

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