編輯:關於 Android 程式設計
最近項目準備嘗試用 WebP 來縮小包體積,於是抽空對相關知識做了調研和學習。至於 WebP 是什麼、有什麼好處,這裡不再贅述,感興趣的同學可以參考相關資料做個大致了解。
入手時大致需要考慮三個問題:如何把現有的 jpeg/png 轉為 WebP?WebP 格式的圖片如何使用?有沒有兼容性問題?下面就跟著這三個問題展開。
官方提供了相互轉化的工具及詳細文檔,可參考 https://developers.google.com/speed/webp/docs/cwebp 。工具的功能列表包含 encode、decode、view 等一系列能力:

首先在 WebP download page 下載工具,這裡下載的是對應 mac os 的 libwebp-0.4.1-mac-10.8-2.tar.gz。解壓後進入 bin 目錄:
MacBook-Pro:bin zhanghongyang01$ pwd /Users/zhanghongyang01/hongyang/works/libwebp-0.4.1-mac-10.8 2/bin MacBook-Pro:bin zhanghongyang01$ ls -l total 5152 -rwxr-xr-x@ 1 zhanghongyang01 staff 1302772 9 20 2014 cwebp -rwxr-xr-x@ 1 zhanghongyang01 staff 421508 9 20 2014 dwebp -rwxr-xr-x@ 1 zhanghongyang01 staff 402128 9 20 2014 gif2webp -rwxr-xr-x@ 1 zhanghongyang01 staff 264588 9 20 2014 vwebp -rwxr-xr-x@ 1 zhanghongyang01 staff 237376 9 20 2014 webpmux
大致有四個命令工具:png 等轉 WebP、WebP 轉 png、gif 轉 WebP、查看 WebP 圖片,最後一個用於創建 WebP 動畫文件。
cwebp weixin.png -o weixin.webp
dwebp weixin.webp -o weixin.png
./gif2webp xingye.gif -o xingye.webp
每個命令都有一堆 options,可以自行研究。
WebP 在 App 中一般用於兩個方面:一是與服務端交互時使用 WebP 圖片,二是應用中的資源文件。
這種方式非常簡單,因為從 Android 4.0 開始就已支持 WebP 圖片。寫個例子,把一張 WebP 圖片放到 assets 目錄:
// 這是一個完全不透明圖的測試
Bitmap bitmap = BitmapFactory.decodeStream(getAssets().open("icon.webp"));
imageView.setImageBitmap(bitmap);
在 4.0.4(API15)的三星手機上運行感覺還不錯。但換上一張部分區域透明的圖片後,發現整個圖都顯示不出來;再換到 4.2.2(API17)手機上卻顯示正常。
查閱文檔可知,官方對 WebP 的支持是這樣寫的:
decode / encode (Android 4.0+) (Lossless, Transparency, Android 4.2.1+)
結合文檔與實驗,大致可得出結論:
4.2.1+ 對 WebP 的 decode、encode 完全支持(包含半透明的 WebP 圖);4.0+ 到 4.2.1 只支持完全不透明的 decode、encode;4.0 以下默認不支持。
如果你的產品最低支持版本高於 4.2.1 就沒問題,否則只能引入 so 做低版本兼容。
官方提供了 WebP 支持的源碼 libwebp-0.5.1.tar.gz。若 NDK 知識足夠,可自行編譯 so;也可以使用前人封裝好的庫,如 webp-android-backport 或 webp-android。這裡選擇後者,把它生成的 so 文件與輔助類 copy 到項目中,也可按其 readme 打包成 aar。
下載 webp-android 後,切換到 webp-android/src/main/jni 目錄執行 ndk-build:
cd webp-android/src/main/jni ndk-build
執行結束後,可在 /webp-android/src/main/libs 目錄下 copy 出所需的 so,若需要其他 CPU 架構,可修改 Application.mk:
/webp-android/src/main/libs
.
├── armeabi
│ └── libwebp_evme.so
├── armeabi-v7a
│ └── libwebp_evme.so
└── x86
└── libwebp_evme.so
再把 WebDecoder 輔助類 copy 到項目中即可,注意保持原有包名。

之後就可以用它提供的 decode 方法:
WebPDecoder.getInstance().decodeWebP(byte[] encoded)
於是原本以 InputStream 為源的代碼可以改寫為:
// 大致的示例代碼
InputStream is = getAssets().open("weixin.webp");
Bitmap bitmap = null;
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN) {
bitmap = WebPDecoder.getInstance().decodeWebP(streamToBytes(is));
} else {
bitmap = BitmapFactory.decodeStream(is);
}
imageView.setImageBitmap(bitmap);
private static byte[] streamToBytes(InputStream is) {
ByteArrayOutputStream os = new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int len;
try {
while ((len = is.read(buffer)) >= 0) {
os.write(buffer, 0, len);
}
} catch (java.io.IOException e) {
}
return os.toByteArray();
}
這樣就能對 4.2.1 以下的 WebP 圖片進行 decode 了。服務端下發 WebP 格式圖片,App 去 decode 顯示即可。
注:webp-android 這個庫只提供了 decode 方法,若需 encode 需自行添加;建議有時間研究源碼,結合 NDK 知識自行生成 so。
除了加載外部圖片,還有個場景是把項目中的資源文件直接替換為 WebP。簡單做法是把 png 轉為 WebP 放到 res/drawable 目錄:

目前有兩個選擇:僅替換不存在局部透明的圖片(項目最小版本為 4.0 時可不引入 so 直接使用);或全部替換(需要引入 so 支持)。
第一種換圖即可。第二種,webp-android 提供了一種做法:
<me.everything.webp.webpimageview
android:layout_height="wrap_content"
android:layout_width="wrap_content"
webp:webp_src="@drawable/your_webp_image" />
但對於已有項目而言,處處改用自定義類還要加屬性實在麻煩,一旦踩坑還得一個個換回去。因此我們需要一種能無縫切換、且易於還原的方式。
最無縫的方式是不動原有布局文件,那麼如何動態讓 ImageView 支持 WebP 呢?其實我們的 SDK 也有類似做法(比如為很多 View 支持 tint 屬性),原理是在根據布局文件創建 View 時做手腳,也就是利用 LayoutInflaterFactory。有了方案,代碼就好寫了:
public class MainActivity extends AppCompatActivity {
private static final int[] LL = new int[] {
android.R.attr.src,
};
@Override
protected void onCreate(Bundle savedInstanceState) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
LayoutInflaterCompat.setFactory(LayoutInflater.from(this), new LayoutInflaterFactory() {
@Override
public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
AppCompatDelegate delegate = getDelegate();
View view = delegate.createView(parent, name, context, attrs);
if (view instanceof ImageView) {
ImageView imageView = (ImageView) view;
TypedArray a = context.obtainStyledAttributes(attrs, LL);
int webpSourceResourceID = a.getResourceId(0, 0);
if (webpSourceResourceID == 0) {
return view;
}
InputStream rawImageStream = getResources().openRawResource(webpSourceResourceID);
byte[] data = streamToBytes(rawImageStream);
final Bitmap webpBitmap = WebPDecoder.getInstance().decodeWebP(data);
imageView.setImageBitmap(webpBitmap);
a.recycle();
}
return view;
}
});
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
一般項目中的 Activity 都存在基類,直接把上述代碼加進去即可。大致邏輯是:對 4.2 以下版本設置一個 LayoutInflaterFactory,創建 ImageView 時取出用戶聲明的 src 屬性,轉為 bitmap 後設置到 ImageView 上。這樣只需把圖換成 WebP 即可,若發現不適合,去掉這段 factory 設置代碼即可還原。
但這裡有個問題:若資源更換不徹底,仍存在部分 png 圖,而 png 在 4.2 以下並不需要上述操作,那麼如何區分 WebP 與非 WebP 呢?可以根據後綴判斷,用下面的方式拿到文件名:
TypedValue value = new TypedValue();
getResources().getValue(webpSourceResourceID, value, true);
String resname = value.string.toString().substring(13, value.string.toString().length());
if (resname.endsWith(".webp")) {
// do
}
當然也可以通過圖片的 header 信息判斷,這種方式更精確。如果你的基類是 FragmentActivity,則直接復寫其 onCreateView 方法即可:
onCreateView(View parent, String name, Context context, AttributeSet attrs) {
final View view = super.onCreateView(parent, name, context, attrs);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
if (view instanceof ImageView) {
ImageView imageView = (ImageView) view;
TypedArray a = context.obtainStyledAttributes(attrs, LL);
int webpSourceResourceID = a.getResourceId(0, 0);
if (webpSourceResourceID == 0) {
return view;
}
TypedValue value = new TypedValue();
getResources().getValue(webpSourceResourceID, value, true);
String resname = value.string.toString().substring(13, value.string.toString().length());
if (resname.endsWith(".webp")) {
InputStream rawImageStream = getResources().openRawResource(webpSourceResourceID);
byte[] data = streamToBytes(rawImageStream);
Bitmap webpBitmap = WebPDecoder.getInstance().decodeWebP(data);
imageView.setImageBitmap(webpBitmap);
}
a.recycle();
}
}
return view;
}
至此,應該對 WebP 有了較全面的認識,也大致了解了在 Android 中使用 WebP 的兼容性問題及處理方式。文中還有很多細節沒有展開,後續踩到的坑會再寫一篇博客記錄。如果你也想用 WebP 縮小 APK,歡迎一起踩坑交流。
從零自定義 Android 控制項(三):打造 View 的彈性滑動
前言 上一篇我們用 scrollTo() 與 scrollBy() 實現了 View 的滑動,但效果相當生硬——滑到位置就戛然而止,缺少過渡感,用戶體驗自然大打折扣。本篇
Android 實現 HorizontalScrollView 內子控件橫向拖拽排序
網上關於 ListView 上下拖動的例子不少,但項目需要橫向拖拽時,合適的參考卻不多。本文記錄一個在橫向容器中通過長按拖拽、重新排列子控件位置的實現,靠的是 Andro
Android 頂部與底部 Tab 導航:TabLayout + ViewPager + Fragment
前言 在 Android 應用中,頂部或底部 Tab 導航是常見的首頁結構。它讓使用者在主要功能間快速切換,也能搭配滑動手勢提升操作流暢度。過去常見做法包括 TabWid
一步一步優化 ListView(二):用 DiskLruCache 打造本地圖片緩存
上一篇介紹了我們通常優化 ListView 的方式,但對於需要加載大量圖片的 ListView 來說,這顯然還不夠。因為我們知道,無論是本地還是網絡的圖片,獲取時的性能都