編輯:關於 Android 程式設計
即使在 4G 時代,行動網路流量仍然是寶貴資源。而在行動網路傳輸中,最佔流量的一種載體就是圖片,這也是行動開發者不得不正視的問題。
我們真正在意的,是圖片體積與品質之間的平衡——希望畫質看起來不錯,同時檔案別太大。Google 給出了一個相當漂亮的答案:WebP。
WebP 是一種圖片檔案格式,在相同的壓縮指標下,它的有損壓縮能比 JPG 小 25% 到 34%。而在我自己的實測中,部分照片甚至能小 50%。
WebP 在 2010 年發布第一個版本,至今已有多年歷史。Google 旗下的各類服務早已廣泛採用,最具代表性的是 YouTube 的影片格式 WebM,正是基於 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.jpg | 5760 kb | 98 kb | 74 kb | 24.49% |
| 2.jpg | 4534 kb | 64 kb | 35 kb | 45.31% |
| 3.jpg | 4751 kb | 93 kb | 68 kb | 26.88% |
| 4.jpg | 7002 kb | 121 kb | 95 kb | 21.49% |
| 5.jpg | 5493 kb | 111 kb | 91 kb | 18.02% |
平均壓縮比約 27.24%
| 檔案 | 原圖 | 壓縮後 JPG | 壓縮後 WebP | 壓縮比 |
|---|---|---|---|---|
| 3.jpg | 4751 kb | 796 kb | 426 kb | 46.48% |
這張 3.jpg 是在室內燈光充足的用餐場景拍攝的。即使完全不縮小解析度、只壓縮品質,仍有 46.48% 的壓縮比,而肉眼幾乎看不出差異。


前面處理的是本機圖片的體積。接下來要把圖片傳到伺服器,這段路徑同樣有優化空間——Gzip。
Gzip 的作用對象是整個請求體,對其中的內容做可逆壓縮,概念近似 PC 上的 zip。使用時需要在標頭加上 Content-Encoding: gzip,而這件事 Retrofit(底層的 OkHttp)會幫你處理好。伺服器收到這類請求後會自動解壓,因此需要後端配合。
要注意的是,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 + Gzip | 169 kb |
| 僅 WebP | 222 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 最佳化的相關文章。
Android 底層實例:耳機插拔檢測與喇叭/聽筒通道切換
Android 底層開發之耳機插拔與音頻通道切換實例 這台設備用的是耳機與麥克分離式的設計,因此需要分別上報事件。排查過程大致是:先確認插拔檢測正常,再確認 ALSA 通
Android Studio 開啟 Eclipse 專案與修正下載而來的 Studio 專案報錯的實用筆記
初次接觸 Android Studio 時,相信不少人都有過一頭霧水的時刻。這篇文章把筆者實際摸索出來的經驗整理出來,和大家一同分享,希望能幫你少走一些彎路。 一、An
Android Fragment 深入解析:生命週期、通訊、事務管理與复用實作
作者:韓曙亮 | 轉載請註明出處:https://blog.csdn.net/shulianghan/article/details/38064191 本文範例程式碼:
Android SQLite 常用命令整理
SQLite 是 Android 中常見的輕量級資料庫,具備佔用資源少、易於嵌入與跨平台等特性。本文整理 Android 開發中常見的 SQLite 概念與命令列操作,方