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

Android WebP 圖片壓縮與傳輸優化實踐

編輯:關於 Android 程式設計

一、為什麼要關注圖片

即使在 4G 時代,行動網路流量仍然是寶貴資源。而在行動網路傳輸中,最佔流量的一種載體就是圖片,這也是行動開發者不得不正視的問題。

我們真正在意的,是圖片體積與品質之間的平衡——希望畫質看起來不錯,同時檔案別太大。Google 給出了一個相當漂亮的答案:WebP。

WebP 是一種圖片檔案格式,在相同的壓縮指標下,它的有損壓縮能比 JPG 小 25% 到 34%。而在我自己的實測中,部分照片甚至能小 50%。

二、生態支持情況

WebP 在 2010 年發布第一個版本,至今已有多年歷史。Google 旗下的各類服務早已廣泛採用,最具代表性的是 YouTube 的影片格式 WebM,正是基於 WebP 的技術構造。此外也有部分國內大型網路服務在特定場景中使用。

三、Android 端:把 JPG 轉為 WebP

以下用 RxJava 做執行緒調度,在 IO 執行緒中批次處理圖片:

String[] imgs = new String[]{"1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jpg"};
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/test/";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    String[] permissions = {
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.READ_PHONE_STATE,
        Manifest.permission.CAMERA
    };
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        requestPermissions(permissions, 0);
    }
    compress();
}

private void compress() {
    Observable.from(imgs)
            .subscribeOn(Schedulers.io())
            .doOnNext(new Action1<String>() {
                @Override
                public void call(String imgName) {
                    compress(imgName);
                }
            })
            .subscribe();
}

private void compress(String imgName) {
    try {
        File file = new File(path, imgName);
        Log.i("compress", "jpg start");
        byte[] bytes = BitmapUtil.compressBitmapToBytes(
                file.getPath(), 600, 0, 60, Bitmap.CompressFormat.JPEG);
        File jpg = new File(path, imgName + "compress.jpg");
        FileUtils.writeByteArrayToFile(jpg, bytes);
        Log.i("compress", "jpg finish");

        Log.i("compress", "webp start");
        byte[] bytes1 = BitmapUtil.compressBitmapToBytes(
                file.getPath(), 600, 0, 60, Bitmap.CompressFormat.WEBP);
        File webp = new File(path, imgName + "compress.webp");
        FileUtils.writeByteArrayToFile(webp, bytes1);
        Log.i("compress", "webp finish");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

測試機為刷了 CyanogenMod 13 的一加 1,因此需要主動請求儲存空間權限。耗時的壓縮操作放在 IO 執行緒執行。

核心的壓縮工具方法:

public static byte[] compressBitmapToBytes(String filePath, int reqWidth,
                                          int reqHeight, int quality,
                                          Bitmap.CompressFormat format) {
    Bitmap bitmap = getSmallBitmap(filePath, reqWidth, reqHeight);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(format, quality, baos);
    byte[] bytes = baos.toByteArray();
    bitmap.recycle();
    Log.i(TAG, "Bitmap compressed success, size: " + bytes.length);
    return bytes;
}

public static Bitmap getSmallBitmap(String filePath, int reqWidth, int reqHeight) {
    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);
}

public static int calculateInSampleSize(BitmapFactory.Options options,
                                        int reqWidth, int reqHeight) {
    int h = options.outHeight;
    int w = options.outWidth;
    int inSampleSize = 0;

    if (h > reqHeight || w > reqWidth) {
        float ratioW = (float) w / reqWidth;
        float ratioH = (float) h / reqHeight;
        inSampleSize = (int) Math.min(ratioH, ratioW);
    }
    return Math.max(1, inSampleSize);
}

先依目標寬高算出縮放比例,再依指定的品質值壓縮,最後把結果寫回本機檔案。這是非常典型的圖片壓縮手法,關鍵在於壓縮時傳入不同的 CompressFormat。

四、實際壓縮效果對比

以下用日常拍攝的照片做簡單對比,測試不算嚴謹,僅供參考。拍攝設備為刷了 CyanogenMod 13 的一加 1,場景都是常見的生活情境。

以下是原圖預覽,檔案太大就不逐張放出了:

縮小解析度,同時壓縮品質

檔案原圖壓縮後 JPG壓縮後 WebP壓縮比
1.jpg5760 kb98 kb74 kb24.49%
2.jpg4534 kb64 kb35 kb45.31%
3.jpg4751 kb93 kb68 kb26.88%
4.jpg7002 kb121 kb95 kb21.49%
5.jpg5493 kb111 kb91 kb18.02%

平均壓縮比約 27.24%

保留原始解析度,僅壓縮品質

檔案原圖壓縮後 JPG壓縮後 WebP壓縮比
3.jpg4751 kb796 kb426 kb46.48%

這張 3.jpg 是在室內燈光充足的用餐場景拍攝的。即使完全不縮小解析度、只壓縮品質,仍有 46.48% 的壓縮比,而肉眼幾乎看不出差異。

五、再用 Gzip 壓一層

前面處理的是本機圖片的體積。接下來要把圖片傳到伺服器,這段路徑同樣有優化空間——Gzip。

Gzip 的作用對象是整個請求體,對其中的內容做可逆壓縮,概念近似 PC 上的 zip。使用時需要在標頭加上 Content-Encoding: gzip,而這件事 Retrofit(底層的 OkHttp)會幫你處理好。伺服器收到這類請求後會自動解壓,因此需要後端配合。

要注意的是,Gzip 對較大且未经壓縮的純文字效果最好。如果請求體本來就很小,就别用了——壓縮包自身的元資料可能比你的內容還大,反而得不償失。

六、用 Retrofit 做請求 Gzip 壓縮

Retrofit 的 Gzip 壓縮本質上是透過 OkHttp 攔截器完成的,流程是:攔截請求 → 加入標頭 → 壓縮內容 → 送出。

/** 這個攔截器會壓縮 HTTP 請求體。注意:並非所有伺服器都能處理! */
final class GzipRequestInterceptor implements Interceptor {
    @Override
    public Response intercept(Interceptor.Chain chain) throws IOException {
        Request originalRequest = chain.request();
        if (originalRequest.body() == null
                || originalRequest.header("Content-Encoding") != null) {
            return chain.proceed(originalRequest);
        }

        Request compressedRequest = originalRequest.newBuilder()
                .header("Content-Encoding", "gzip")
                .method(originalRequest.method(), gzip(originalRequest.body()))
                .build();
        return chain.proceed(compressedRequest);
    }

    private RequestBody gzip(final RequestBody body) {
        return new RequestBody() {
            @Override
            public MediaType contentType() {
                return body.contentType();
            }

            @Override
            public long contentLength() {
                return -1; // 事先無法得知壓縮後的長度
            }

            @Override
            public void writeTo(BufferedSink sink) throws IOException {
                BufferedSink gzipSink = Okio.buffer(new GzipSink(sink));
                body.writeTo(gzipSink);
                gzipSink.close();
            }
        };
    }
}

七、抓包驗證實際傳輸量

用 Fiddler 4 監看整個請求過程,就能知道實際傳出去的資料有多大。

以下是同時上傳兩張圖片時的請求體大小:

方案請求體大小
WebP + Gzip169 kb
僅 WebP222 kb

加上 Gzip 之後又小了約 23%

把數字串起來看:WebP 比 JPG 小約 27%,而 WebP 疊上 Gzip 又比單純 WebP 小 23%。兩層疊加省下來的流量相當可觀。

八、實務上的幾點提醒

WebP 預設支援 Android 4.0 以上。若你的專案最低支援到 API 16,那完全沒問題;如果還要往下相容到 2.x,雖有第三方方案,但通常意味著專案本身的技術債已經需要處理了。

就照片傳輸這個角度來看,WebP 不僅節省使用者流量,也能加快圖片載入速度,收益相當明確。反過來,如果還是有人用「iOS 做不了」或「後端不配合」當理由直接放棄,那實在有些可惜——這類跨端優化通常需要前端主動把量測數據拿出來溝通。

延伸閱讀方向:WebP 的產品視角介紹、後端串接說明、Google 官方文件,以及 InfoQ 與 CSDN 上關於 SDK 最佳化的相關文章。

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