編輯:關於 Android 程式設計
手機鏡頭的解析度一路水漲船高,隨便一張照片就有好幾 MB。當 App 需要把拍下的照片上傳到伺服器時,這龐大的體積會直接反映在等待時間與行動網路流量上。的解法有兩條路:一是拍攝時就要求系統給縮圖,二是拍下原圖後自行壓縮。前者實作最省事,但畫質往往慘不忍睹;後者能在可接受範圍內兼顧清晰度與檔案大小,是正式專案裡更常採用的做法。
完整流程可以拆成三個步驟:降採樣解碼(避免大圖直接載入造成 OutOfMemoryError)、依 EXIF 校正方向(避免照片躺著)、重新編碼並調整品質。以下逐步說明。
關鍵在於 inJustDecodeBounds。設為 true 時,BitmapFactory 只解析檔案標頭取得寬高,不會真正配置像素記憶體。拿到原始尺寸後,再透過 inSampleSize 指定降採樣倍數,第二次解碼時記憶體用量就降到 1/n²。
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
// 依目標尺寸計算 inSampleSize
options.inSampleSize = calculateInSampleSize(options, 480, 800);
// 正式解碼
options.inJustDecodeBounds = false;
Bitmap bm = BitmapFactory.decodeFile(filePath, options);
private 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 heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// 取較大者,確保結果尺寸仍不小於需求
inSampleSize = heightRatio < widthRatio ? widthRatio : heightRatio;
}
return inSampleSize;
}
手機為了省下運算,多半是寫入方向資訊而非真的旋轉像素。若不處理,同一張照片在不同 App 裡會呈現不同角度。用 ExifInterface 取出方向標籤,再用 Matrix 補做旋轉即可。
private static int readPictureDegree(String path) {
int degree = 0;
try {
ExifInterface exifInterface = new ExifInterface(path);
int orientation = exifInterface.getAttributeInt(
ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90: degree = 90; break;
case ExifInterface.ORIENTATION_ROTATE_180: degree = 180; break;
case ExifInterface.ORIENTATION_ROTATE_270: degree = 270; break;
}
} catch (IOException e) {
e.printStackTrace();
}
return degree;
}
private static Bitmap rotateBitmap(Bitmap bitmap, int rotate) {
if (bitmap == null) return null;
int w = bitmap.getWidth();
int h = bitmap.getHeight();
Matrix mtx = new Matrix();
mtx.postRotate(rotate);
return Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, true);
}
compress() 的第二個參數就是 JPEG 品質值,範圍 0~100。傳 100 代表幾乎不做有損壓縮,傳 30 大約砍掉七成體積。實務上 50~80 之間通常是清晰度與大小的甜蜜點,涉及文字或票券的圖片則建議拉高到 80 以上。
bm.compress(Bitmap.CompressFormat.JPEG, 30, baos);
// 30 代表壓縮掉約 70%;100 則表示不壓縮
public static Bitmap getSmallBitmap(String filePath) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
options.inSampleSize = calculateInSampleSize(options, 480, 800);
options.inJustDecodeBounds = false;
Bitmap bm = BitmapFactory.decodeFile(filePath, options);
if (bm == null) {
return null;
}
int degree = readPictureDegree(filePath);
bm = rotateBitmap(bm, degree);
ByteArrayOutputStream baos = null;
try {
baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 30, baos);
} finally {
try {
if (baos != null) baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return bm;
}
這段程式回傳的是 Bitmap 物件,若目的是上傳,通常還需要再把它寫回檔案或轉成 byte[],並記得在不再使用時呼叫 recycle(),否則在圖片串流處理的場景裡很容易累積記憶體壓力。另外 ByteArrayOutputStream 會把整張圖暫存在記憶體中,若圖片偏大,改用 FileOutputStream 直接寫檔會更省。
若專案的 minSdk 已達較新版本,也可考慮改用 BitmapRegionDecoder 或 Android 內建的 ImageDecoder/BitmapFactory 搭配 Bitmap.Config.RGB_565 等策略進一步降低記憶體佔用;概念與本文一致,都是「先量尺寸、再降採樣、最後編碼」。
Android 多執行緒與 Handler 的實用指南
當我們需要執行一些耗時操作時——比如發起一條網路請求——考慮到網速等種種因素,伺服器未必會立刻回應。如果不把這類操作放到子執行緒裡執行,就會導致主執行緒被阻塞,進而影響使
我的 Android 進階之旅——查看應用簽名信息
一、查看自己的證書簽名信息 如上一篇《我的 Android 進階之旅——製作和查看自訂的 Debug 版本簽名證書》所述,我們可以透過 keytool 命令查看生成的 k
Android 中監聽 ScrollView 滑動事件的實現
有時候我們需要實時掌握 ScrollView 的滑動情況,例如滑動了多少距離、是否已經滑到頂部或底部。遺憾的是 SDK 並沒有直接提供對外的方法,只保留了一個 prote
OpenGL ES 紋理繪製入門(一)
矩陣變換類 package test.com.opengles7_1; import android.opengl.Matrix; /** * Created by h