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

Android 圖片工具類 ImageUtil 完整實作與源碼解析

編輯:關於 Android 程式設計

幾乎每個 App 都會需要處理圖片:裁頭像、做圓角、產生縮圖、抓取影片封面、在 Bitmap/Drawable/byte[] 之間轉換。這些邏輯零散又重複,實在該整理成一個工具類。本文把這些常用操作一次打包。

涵蓋範圍:系統裁圖、Bitmap 圓角、縮略圖、影片縮略圖、各類型互轉。


一、呼叫系統內建裁圖

/**
 * 呼叫系統自帶裁圖工具
 */
public static void cropPicture(Activity activity, int size, Uri uri, int action, File cropFile) {
    try {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", size);
        intent.putExtra("outputY", size);
        intent.putExtra("scale", true);
        intent.putExtra("scaleUpIfNeeded", true);
        intent.putExtra("return-data", false);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cropFile));
        activity.startActivityForResult(intent, action);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

/** 預設裁成 250x250 */
public static void cropPicture(Activity activity, Uri uri, int action, File cropFile) {
    cropPicture(activity, 250, uri, action, cropFile);
}

/** 建立檔案並裁圖,回傳結果檔案 */
public static File cropPicture(Activity activity, Uri uri, int action,
                               String appName, Application application) {
    File resultFile = createImageFile(appName, application);
    cropPicture(activity, 250, uri, action, resultFile);
    return resultFile;
}

/** 依時間戳產生圖片檔 */
@SuppressLint("SimpleDateFormat")
public static File createImageFile(String appName, Application application) {
    File folder = createImageFileInCameraFolder(appName, application);
    String filename = new SimpleDateFormat("yyyyMMddHHmmss").format(System.currentTimeMillis());
    return new File(folder, filename + ".jpg");
}

public static File createImageFileInCameraFolder(String appName, Application application) {
    String folder = createAPPFolder(appName, application);
    File file = new File(folder, "image");
    if (!file.exists()) {
        file.mkdirs();
    }
    return file;
}

/** 建立 App 專屬資料夾,優先使用 SD 卡 */
public static String createAPPFolder(String appName, Application application,
                                     String folderName) {
    File root = Environment.getExternalStorageDirectory();
    File folder;

    if (DeviceUtil.isSDCardAvailable() && root != null) {
        folder = new File(root, appName);
        if (!folder.exists()) folder.mkdirs();
    } else {
        // 無 SD 卡時退回 cache 目錄
        root = application.getCacheDir();
        folder = new File(root, appName);
        if (!folder.exists()) folder.mkdirs();
    }

    if (folderName != null) {
        folder = new File(folder, folderName);
        if (!folder.exists()) folder.mkdirs();
    }
    return folder.getAbsolutePath();
}

二、Bitmap 圓角

/**
 * 取得圓角 Bitmap(使用 SRC_IN 混合模式)
 */
public static Bitmap getRoundedCornerBitmap(Bitmap srcBitmap, float radius) {
    Bitmap resultBitmap = Bitmap.createBitmap(
            srcBitmap.getWidth(), srcBitmap.getHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(resultBitmap);
    Paint paint = new Paint();
    Rect rect = new Rect(0, 0, srcBitmap.getWidth(), srcBitmap.getHeight());
    RectF rectF = new RectF(rect);

    paint.setAntiAlias(true);
    canvas.drawARGB(0, 0, 0, 0);
    paint.setColor(0xBDBDBE);
    // 先畫圓角矩形當遮罩
    canvas.drawRoundRect(rectF, radius, radius, paint);
    // 只保留與遮罩交集的部分
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
    canvas.drawBitmap(srcBitmap, rect, rect, paint);
    return resultBitmap;
}

這裡用的是 SRC_IN 而不是圓角 ImageView 常用的 DST_IN,差別在於先畫的是遮罩形狀、後畫的是原圖。兩種順序都能得到圓角,選用哪一種取決於你的繪製次序。

三、縮圖與解析

/** 產生縮圖檔並回傳路徑 */
public static String getThumbnailImage(String path, int targetWidth) {
    Bitmap scaleImage = decodeScaleImage(path, targetWidth, targetWidth);
    try {
        File file = File.createTempFile("image", ".jpg");
        FileOutputStream fos = new FileOutputStream(file);
        scaleImage.compress(Bitmap.CompressFormat.JPEG, 60, fos);
        fos.close();
        return file.getAbsolutePath();
    } catch (Exception e) {
        e.printStackTrace();
        return path;
    }
}

/** 解析資源圖並依目標尺寸縮放(兩次解碼技巧) */
public static Bitmap decodeScaleImage(Context context, int resId,
                                      int targetWidth, int targetHeight) {
    BitmapFactory.Options options = new BitmapFactory.Options();
    // 第一次只讀邊界,不真正配置記憶體
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(context.getResources(), resId, options);

    options.inSampleSize = calculateInSampleSize(options, targetWidth, targetHeight);
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(context.getResources(), resId, options);
}

/** 計算 inSampleSize,取寬高比例中較大者確保填滿 */
public static int calculateInSampleSize(BitmapFactory.Options options,
                                        int targetWidth, int targetHeight) {
    int height = options.outHeight;
    int width = options.outWidth;
    int scale = 1;
    if (height > targetHeight || width > targetWidth) {
        int heightScale = Math.round((float) height / (float) targetHeight);
        int widthScale = Math.round((float) width / (float) targetWidth);
        scale = Math.max(heightScale, widthScale);
    }
    return scale;
}

/** 只讀圖片邊界資訊 */
public static BitmapFactory.Options getBitmapOptions(String pathName) {
    BitmapFactory.Options opts = new BitmapFactory.Options();
    opts.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(pathName, opts);
    return opts;
}

/** 讀取照片的 EXIF 旋轉角度 */
public static int readPictureDegree(String filename) {
    int degree = 0;
    try {
        ExifInterface exifInterface = new ExifInterface(filename);
        int orientation = exifInterface.getAttributeInt(
                ExifInterface.TAG_ORIENTATION, 1);
        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;
            default:
                break;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return degree;
}

/** 依角度旋轉 Bitmap */
public static Bitmap rotatingImageView(int degree, Bitmap source) {
    Matrix matrix = new Matrix();
    matrix.postRotate((float) degree);
    return Bitmap.createBitmap(source, 0, 0,
            source.getWidth(), source.getHeight(), matrix, true);
}

兩次解碼(decode bounds trick)是這裡最值得記的技巧:先把 inJustDecodeBounds 設為 true,此時 decodeFile 只會去讀檔頭取得寬高,不會真正配置像素記憶體;算出 inSampleSize 後再關掉這個旗標做真正的解碼。這樣可以避免把一張 4000x3000 的大圖整個載入而引發 OOM。

EXIF 方向不可忽略。手機拍攝時為了省電力,多半不會真的旋轉感光元件,而是把方向寫在 EXIF 裡。若不讀取並補做旋轉,使用者看到的照片會是躺倒的——這是圖片上傳功能最常見的 bug。

四、影片縮圖

/** 取得影片縮圖 Bitmap */
public static Bitmap getVideoThumbnail(String filePath, int width, int height, int kind) {
    Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(filePath, kind);
    return ThumbnailUtils.extractThumbnail(bitmap, width, height,
            ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
}

/** 儲存影片縮圖並回傳路徑 */
public static String saveVideoThumbnail(File file, int width, int height, int kind) {
    Bitmap videoThumbnail = getVideoThumbnail(file.getAbsolutePath(), width, height, kind);
    File thumbFile = new File(PathUtil.getInstance().getVideoPath(), "th_" + file.getName());
    try {
        thumbFile.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
    }
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(thumbFile);
        videoThumbnail.compress(Bitmap.CompressFormat.JPEG, 100, fos);
        fos.flush();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (fos != null) {
            try { fos.close(); } catch (IOException e) { e.printStackTrace(); }
        }
    }
    return thumbFile.getAbsolutePath();
}

五、型別互轉

/** 資源 ID → byte[] */
public static byte[] toByteArray(Context context, int imageResourceId) {
    Bitmap bitmap = toBitmap(context, imageResourceId);
    return (bitmap != null) ? toByteArray(bitmap) : null;
}

/** ImageView → byte[] */
public static byte[] toByteArray(ImageView imageView) {
    Bitmap bitmap = toBitmap(imageView);
    if (bitmap != null) return toByteArray(bitmap);
    Log.w(TAG, "the ImageView imageView content was invalid");
    return null;
}

/** byte[] → Bitmap */
public static Bitmap toBitmap(byte[] imageData) {
    if (imageData != null && imageData.length != 0) {
        return BitmapFactory.decodeByteArray(imageData, 0, imageData.length);
    }
    Log.w(TAG, "the byte[] imageData content was invalid");
    return null;
}

/** 資源 ID → Bitmap */
public static Bitmap toBitmap(Context context, int imageResourceId) {
    Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), imageResourceId);
    if (bitmap != null) return bitmap;
    Log.w(TAG, "the int imageResourceId content was invalid");
    return null;
}

/** ImageView → Bitmap */
public static Bitmap toBitmap(ImageView imageView) {
    if (imageView.getDrawable() != null) {
        return toBitmap(imageView.getDrawable());
    }
    return null;
}

/** Bitmap → byte[] */
public static byte[] toByteArray(Bitmap bitmap) {
    if (bitmap != null) {
        int size = bitmap.getWidth() * bitmap.getHeight() * 4;
        ByteArrayOutputStream baos = new ByteArrayOutputStream(size);
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        return baos.toByteArray();
    }
    Log.w(TAG, "the Bitmap bitmap content was invalid");
    return null;
}

/** Drawable → Bitmap */
public static Bitmap toBitmap(Drawable drawable) {
    if (drawable != null) {
        BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
        return bitmapDrawable.getBitmap();
    }
    Log.w(TAG, "the Drawable drawable content was invalid");
    return null;
}

/** Bitmap → Drawable */
public static Drawable toDrawable(Bitmap bitmap) {
    if (bitmap != null) {
        return new BitmapDrawable(bitmap);
    }
    Log.w(TAG, "the Bitmap bitmap content was invalid");
    return null;
}

實務上的幾個提醒

Material 版本的 BitmapDrawable 建構子已棄用。直接 new BitmapDrawable(bitmap) 在新版 SDK 會出現警告,建議改用 new BitmapDrawable(resources, bitmap), density 的處理才會正確。

裁圖的隱含相容問題。com.android.camera.action.CROP 並非官方標準 API,各家 ROM 的圖庫實作不一,部分機型會直接沒有回應。另外 Android 7.0(API 24)起 Uri.fromFile() 會觸發 FileUriExposedException,必須改用 FileProvider.getUriForFile() 並授予 FLAG_GRANT_WRITE_URI_PERMISSION。若專案 targetSdk 較新,這段裁圖程式需要改寫。

記得 recycle。Bitmap 佔的是原生記憶體,大量處理時要在用完后呼叫 recycle()(Android 8.0 以上記憶體管理已改由 GC 完全接手,recycle() 不再是必須,但早期版本仍建議呼叫)。

圖片載入請用成熟函式庫。Glide、Coil、Fresco 都已經把記憶體快取、磁碟快取、生命週期綁定、請求取消做得很完整。上面的工具類適合處理「一次性、小數量」的圖片操作(例如裁頭像後處理一次),若是在清單中大量載圖,請直接用函式庫。

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