編輯:關於 Android 程式設計
Bitmap 是 Android 圖片處理的核心類別,但各種轉換場景(Drawable、byte[]、檔案、資源)散落在不同 API 裡,用時總要重新查。以下把常見用法整理成一份速查表。
public static Bitmap drawableToBitmap(Drawable drawable) {
Bitmap bitmap = Bitmap.createBitmap(
drawable.getIntrinsicWidth(),
drawable.getIntrinsicHeight(),
drawable.getOpacity() != PixelFormat.OPAQUE
? Bitmap.Config.ARGB_8888
: Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
drawable.draw(canvas);
return bitmap;
}
這裡的 Config 選擇有講究:若 Drawable 不透明就用 RGB_565(每像素 2 位元組,省一半記憶體),否則用 ARGB_8888 保留透明通道。
Resources res = getResources(); Bitmap bmp = BitmapFactory.decodeResource(res, R.drawable.pic);
private byte[] Bitmap2Bytes(Bitmap bm) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}
private Bitmap Bytes2Bimap(byte[] b) {
if (b.length != 0) {
return BitmapFactory.decodeByteArray(b, 0, b.length);
} else {
return null;
}
}
static boolean saveBitmap2file(Bitmap bmp, String filename) {
CompressFormat format = Bitmap.CompressFormat.JPEG;
int quality = 100;
OutputStream stream = null;
try {
stream = new FileOutputStream("/sdcard/" + filename);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return bmp.compress(format, quality, stream);
}
實際專案請改用 Environment.getExternalStorageDirectory() 或 App 專屬目錄 getExternalFilesDir(),並在 Android 10 以上採用 MediaStore 或 SAF,避免寫死路徑與要求 bulky 的儲存權限。
// 讀取圖片來源
Bitmap bm = BitmapFactory.decodeStream(
getResources().openRawResource(R.drawable.dog));
int width = bm.getWidth();
int height = bm.getHeight();
// 設定想要的尺寸
int newWidth = 320;
int newHeight = 480;
// 計算縮放比例
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// 建立 Matrix 並設定縮放參數
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
// 產生新的 Bitmap
Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
// 畫到畫布上
canvas.drawBitmap(newbm, 0, 0, paint);
Bitmap bt = BitmapFactory.decodeFile("/sdcard/myImage/" + "head.jpg");
public Bitmap drawableToBitamp(int drawableResource) {
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inPreferredConfig = Bitmap.Config.RGB_565;
opt.inPurgeable = true;
opt.inInputShareable = true;
InputStream is = this.getResources().openRawResource(drawableResource);
return BitmapFactory.decodeStream(is, null, opt);
}
以上都是基礎轉換,但真正在專案裡最常遇到的問題是記憶體。幾個實用技巧:
用 inSampleSize 做降採樣。這是控制解碼時記憶體占用的最有效手段:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true; // 第一次只讀尺寸,不配置像素記憶體
BitmapFactory.decodeFile(path, options);
int sampleSize = 1;
while (options.outWidth / (sampleSize * 2) > targetWidth
&& options.outHeight / (sampleSize * 2) > targetHeight) {
sampleSize *= 2;
}
options.inSampleSize = sampleSize;
options.inJustDecodeBounds = false; // 第二次才真正解碼
return BitmapFactory.decodeFile(path, options);
用 recycle() 明確釋放(Android 3.0 以下必要,之後 Bitmap 像素記憶體已改由 managed heap 配置,過度呼叫 recycle 反而容易造成使用已回收物件的 crash)。
善用複用池。inBitmap 可讓解碼時複用既有記憶體區塊,是 Android 4.4 之後降低 GC 抖動的關鍵設定:
options.inBitmap = reusableBitmap; options.inMutable = true;
最後,若只是要在清單中顯示網路圖片,別自己折騰 BitmapFactory,直接用 Glide、Coil 或 Picasso,它們已把降採樣、快取、生命週期管理與 recycle 都處理妥當。
Android 支付寶 SDK 整合常見錯誤排查
最近在做支付功能,踩到的坑先整理下來,都是回報率極高、但錯誤訊息本身幾乎沒有線索的幾個問題。 resultStatus={4001};memo={參數錯誤} 看起來像參數
自定義時間軸 View 的實作步驟拆解
時間軸看起來有點花俏,實際上就是 ListView 裡一列又一列的項目擺在一起,加上一個自繪的圓形節點而已。只要盯著「單一項目」看,事情就單純了。 相關影片: Andro
Android Studio 2.1 快速接入第三方短信驗證 SDK 實作指南
前言 初次整合第三方類庫時,常因流程不熟而卡關。本文以 Android Studio 2.1 為例,示範如何快速完成短信驗證碼功能。 1. 註冊 Mob 帳號 前往 Mo
在 Eclipse 中使用 Android Studio Gradle AAR 庫的完整指南
為何需要在 Eclipse 中使用 AAR許多新的 Android 庫以 Android Studio 的 Gradle 專案形式發布,並以 AAR 形式進入公共倉庫。然