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

Android 圖片壓縮四大實戰技巧

編輯:關於 Android 程式設計

行動裝置的記憶體與儲存空間都相當有限,上傳或快取圖片時往往需要經過壓縮。本文整理四種常見的壓縮思路,從裁切、降質、縮放像素,到兩者結合,並附上可直接套用的程式碼。

第一種:裁切以達到壓縮目的

透過裁掉多餘的邊緣區域,直接減少像素數量,是最直截了當的方式。

第二種:降低圖片品質(降質)

使用 Bitmap.compress(CompressFormat format, int quality, OutputStream stream) 這個方法即可降質。參數說明:format 是壓縮後的格式,quality 是壓縮後的品質(0 最低、100 不壓縮),stream 則是壓縮結果的輸出流。

/**
 * 多執行緒壓縮圖片的品質
 * @param bitmap  記憶體中的圖片
 * @param imgPath 圖片的保存路徑
 */
public static void compressImageByQuality(final Bitmap bitmap, final String imgPath) {
    new Thread(new Runnable() { // 開啟多執行緒進行壓縮
        @Override
        public void run() {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int options = 100;
            // 質量壓縮,100 表示不壓縮,0 表示壓到最小
            bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);
            // 若壓縮後仍大於 100kb,繼續降質
            while (baos.toByteArray().length / 1024 > 100) {
                baos.reset();       // 重置,讓下次寫入覆蓋先前內容
                options -= 10;      // 每次減少 10
                if (options < 0) options = 0;
                bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);
                if (options == 0) break;
            }
            try {
                FileOutputStream fos = new FileOutputStream(new File(imgPath));
                fos.write(baos.toByteArray());
                fos.flush();
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }).start();
}

由於此方法包含 I/O 操作與迴圈,較為耗時,因此用多執行緒處理,避免阻塞主執行緒。

第三種:按比例縮小像素

透過 BitmapFactory.Options 的 inSampleSize 設定採樣率,讓圖片以縮小的解析度載入記憶體,再輸出到本機,藉此達到縮減像素的目的。

/**
 * 按比例縮小圖片的像素以達到壓縮目的
 * @param imgPath
 */
public static void compressImageByPixel(String imgPath) {
    BitmapFactory.Options newOpts = new BitmapFactory.Options();
    newOpts.inJustDecodeBounds = true; // 只讀邊界,不載入內容
    Bitmap bitmap = BitmapFactory.decodeFile(imgPath, newOpts);
    newOpts.inJustDecodeBounds = false;
    int width = newOpts.outWidth;
    int height = newOpts.outHeight;
    float maxSize = 1000f; // 預設最大 1000px
    int be = 1;
    if (width > height && width > maxSize) {
        be = (int) (newOpts.outWidth / maxSize);
    } else if (width < height && height > maxSize) {
        be = (int) (newOpts.outHeight / maxSize);
    }
    be++;
    newOpts.inSampleSize = be;             // 設定採樣率
    newOpts.inPreferredConfig = Config.ARGB_8888; // 預設模式,可不設
    newOpts.inPurgeable = true;            // 需與下行同時設定才有效
    newOpts.inInputShareable = true;       // 記憶體不足時圖片可被回收
    bitmap = BitmapFactory.decodeFile(imgPath, newOpts);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    try {
        FileOutputStream fos = new FileOutputStream(new File(imgPath));
        fos.write(baos.toByteArray());
        fos.flush();
        fos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

這裡有個關鍵技巧:先用 inJustDecodeBounds = true 只讀取圖片尺寸而不真正載入像素,計算出合適的採樣率後,再以 inSampleSize 正式解碼,能有效避免大圖直接載入造成的 OutOfMemoryError。

第四種:先縮放像素、再降質

把第二、三種方法結合起來,效果最好:先按比例縮小尺寸,再對縮放後的圖做品質壓縮。

public static void compressImageByQuality(final Bitmap bitmap, final String imgPath) {
    new Thread(new Runnable() {
        @Override
        public void run() {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int options = 100;
            bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);
            while (baos.toByteArray().length / 1024 > 100) {
                baos.reset();
                options -= 10;
                if (options < 0) options = 0;
                bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);
                if (options == 0) break;
            }
            try {
                FileOutputStream fos = new FileOutputStream(new File(imgPath));
                fos.write(baos.toByteArray());
                fos.flush();
                fos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }).start();
}

public static void compressImageByPixel(String imgPath) {
    BitmapFactory.Options newOpts = new BitmapFactory.Options();
    newOpts.inJustDecodeBounds = true;
    Bitmap bitmap = BitmapFactory.decodeFile(imgPath, newOpts);
    newOpts.inJustDecodeBounds = false;
    int width = newOpts.outWidth;
    int height = newOpts.outHeight;
    float maxSize = 1000f;
    int be = 1;
    if (width > height && width > maxSize) {
        be = (int) (newOpts.outWidth / maxSize);
    } else if (width < height && height > maxSize) {
        be = (int) (newOpts.outHeight / maxSize);
    }
    be++;
    newOpts.inSampleSize = be;
    newOpts.inPreferredConfig = Config.ARGB_8888;
    newOpts.inPurgeable = true;
    newOpts.inInputShareable = true;
    bitmap = BitmapFactory.decodeFile(imgPath, newOpts);
    compressImageByQuality(bitmap, imgPath); // 縮放好尺寸後,再進行質量壓縮
}

實際專案中,第四種「先縮放、再降質」的組合拳往往能在畫質與檔案大小之間取得最佳平衡,是最值得推薦的做法。

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