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

更好用的 Android 圖片壓縮工具類(含源碼)

編輯:關於 Android 程式設計

做圖片壓縮很久了,早期大家普遍採用 Google 官方文檔裡的采樣壓縮方案。它的核心思路是先用 inJustDecodeBounds 讀取圖片的原始尺寸,再計算合適的 inSampleSize 進行降采樣:

final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);

public 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 halfHeight = height / 2;
        final int halfWidth = width / 2;
        while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) {
            inSampleSize *= 2;
        }
    }
    return inSampleSize;
}

仔細看 calculateInSampleSize 你會發現,inSampleSize 的取值是按 2 → 4 → 8 這樣的 2 的倍數遞增的,而且進入 while 循環時寬高已經被當成「減半後」來判斷了。這個算法適合原圖與目標尺寸差距極大的場景(比如把 12M 壓到 0.75M),但對於安卓手機內部「2M 壓到 100K」這類差距不算懸殊的情況,顯得過於粗放。

針對安卓端的實際壓縮需求,我對它做了改進:把壓縮倍數從 2 → 4 → 8 改為逐 1 遞增的 2 → 3 → 4,讓結果更貼近目標尺寸。

/**
 * 計算壓縮比例值(改進版 by touch_ping)
 * 原版:2 > 4 > 8 ... 倍壓縮
 * 當前:2 > 3 > 4 ... 倍壓縮
 */
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
    final int picheight = options.outHeight;
    final int picwidth = options.outWidth;
    int targetheight = picheight;
    int targetwidth = picwidth;
    int inSampleSize = 1;
    if (targetheight > reqHeight || targetwidth > reqWidth) {
        while (targetheight >= reqHeight && targetwidth >= reqWidth) {
            inSampleSize += 1;
            targetheight = picheight / inSampleSize;
            targetwidth = picwidth / inSampleSize;
        }
    }
    return inSampleSize;
}

經過這樣的調整,同一張圖的體積從 1.12M 降到了約 81.75K,效果立竿見影。

完整壓縮工具類

下面附上整理好的完整工具類,涵蓋質量壓縮、從資源/文件/Bitmap 降采樣加載,以及改進版的尺寸計算:

package com.example.mqtest;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

/**
 * 圖片壓縮工具類
 * @author touch_ping
 */
public class BitmapCompressor {

    /**
     * 質量壓縮
     * @param image  待壓縮圖片
     * @param maxkb  目標大小(KB)
     */
    public static Bitmap compressBitmap(Bitmap image, int maxkb) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos); // 100 表示不壓縮
        int options = 100;
        while (baos.toByteArray().length / 1024 > maxkb) {
            baos.reset();          // 清空 baos
            options -= 10;         // 每次減少 10
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        return BitmapFactory.decodeStream(isBm, null, null);
    }

    /** 從資源降采樣加載 */
    public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(res, resId, options);
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeResource(res, resId, options);
    }

    /** 從文件降采樣加載 */
    public static Bitmap decodeSampledBitmapFromFile(String filepath, int reqWidth, int reqHeight) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filepath, options);
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(filepath, options);
    }

    /** 從 Bitmap 降采樣加載 */
    public static Bitmap decodeSampledBitmapFromBitmap(Bitmap bitmap, int reqWidth, int reqHeight) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 90, baos);
        byte[] data = baos.toByteArray();
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeByteArray(data, 0, data.length, options);
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeByteArray(data, 0, data.length, options);
    }

    /** 改進版的壓縮比例計算 */
    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        final int picheight = options.outHeight;
        final int picwidth = options.outWidth;
        int targetheight = picheight;
        int targetwidth = picwidth;
        int inSampleSize = 1;
        if (targetheight > reqHeight || targetwidth > reqWidth) {
            while (targetheight >= reqHeight && targetwidth >= reqWidth) {
                inSampleSize += 1;
                targetheight = picheight / inSampleSize;
                targetwidth = picwidth / inSampleSize;
            }
        }
        return inSampleSize;
    }
}

這個工具類同時覆蓋了「質量壓縮」與「尺寸降采樣」兩條路徑,能滿足大多數安卓場景下的圖片體積優化需求。實際項目中,可根據對清晰度與文件大小的具體要求靈活挑選合適的方法。

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