編輯:Android 開發實例
手機相機的解析度越來越高,一張照片動輒好幾 MB。若要把拍好的照片上傳到伺服器,在網速不佳的環境下不但緩慢,還會消耗大量行動數據。解決方式有兩條路:一是直接請相機拍小圖,二是把大圖壓縮。前者簡單但清晰度差,後者能在維持可接受畫質的前提下大幅縮小檔案,是實務上更常用的做法。
本文示範後者,完整流程包含三個步驟:取樣縮放、依 EXIF 校正角度、品質壓縮。
直接把一張幾千萬畫素的圖片載入記憶體,幾乎一定會 OOM。正確做法是先只讀取圖片的尺寸資訊(不載入像素),算出合適的取樣率,再進行真正的解碼。
final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; // 只讀邊界,不載入像素 BitmapFactory.decodeFile(filePath, options); // 計算 inSampleSize options.inSampleSize = calculateInSampleSize(options, 480, 800); // 以 inSampleSize 真正解碼 options.inJustDecodeBounds = false; Bitmap bm = BitmapFactory.decodeFile(filePath, options);
inJustDecodeBounds = true 是關鍵技巧:此時 decodeFile 會把 outWidth、outHeight 填進 options 卻不實際配置記憶體,讓我們能先知道尺寸再決定縮放比例。
手機拍攝時常因為握持方向而寫入旋轉資訊,若不處理,壓縮後的照片會是橫躺的。
int degree = readPictureDegree(filePath); bm = rotateBitmap(bm, degree);
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);
}
createBitmap 最後一個參數传 true 代表啟用雙線性濾波,旋轉後的邊緣會比較平滑。
bm.compress(Bitmap.CompressFormat.JPEG, 30, baos); // 30 代表品質 30%,約等於壓縮 70%;100 則是不壓縮
public static Bitmap getSmallBitmap(String filePath) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
// 計算 inSampleSize
options.inSampleSize = calculateInSampleSize(options, 480, 800);
// 以 inSampleSize 解碼
options.inJustDecodeBounds = false;
Bitmap bm = BitmapFactory.decodeFile(filePath, options);
if (bm == null) {
return null;
}
// 依 EXIF 校正角度
int degree = readPictureDegree(filePath);
bm = rotateBitmap(bm, degree);
ByteArrayOutputStream baos = null;
try {
baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 30, baos);
} finally {
if (baos != null) {
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return bm;
}
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
inSampleSize = heightRatio < widthRatio ? widthRatio : heightRatio;
}
return inSampleSize;
}
inSampleSize 只能是整數,且實際解碼時會被取 2 的次方(1、2、4、8……)。範例中取較大的比例,可保證縮放後的寬高都不會小於目標值。
· 範例中的 compress() 只是把結果寫進 ByteArrayOutputStream,並沒有真的存檔。若要寫回檔案,需再將 baos 的內容輸出到 FileOutputStream。
· 此方法回傳的 Bitmap 使用完畢後記得呼叫 recycle(),否則在記憶體受限的舊版裝置上容易 OOM。
· 若需要「檔案大小盡量小」,比 compress 更有效率的做法是縮小尺寸本身;若需要「尺寸固定但檔案更小」,則降低品質參數。
· Android 4.4 以後可使用 BitmapFactory.Options.inPreferredConfig 搭配 ARGB_8888/RGB_565 控制每像素位元數,RGB_565 可再省一半記憶體(但沒有 alpha 通道)。
· 讀取外部檔案需在 Manifest 宣告 READ_EXTERNAL_STORAGE 或新版的分項媒體權限。
· 若只是要縮圖上傳,可直接使用 ExifInterface 搭配 sampling,或改用成熟函式庫(如 Glide 的 submit(width, height))處理,能省下不少邊角問題。
Android 讀取網路 JSON:從字串到可用物件的三個步驟
行動裝置上的資料多半來自網路,而網路上的資料多半是 JSON。JSON 的全名是 JavaScript Object Notation,是一種不依附任何平台的純文字資料格
Android XML 解析三大方式詳解:SAX、Pull 與 DOM
在 Android 開發中,解析 XML 文件是家常便飯。常見的方式有三種:SAX、Pull 和 DOM。本文以一個具體的 channels.xml 為例,對這三種解析方
Android 進階:SurfaceView 與多線程混搭實例
前文簡單介紹了 Android 中 SurfaceView 的基本用法,本文則進一步探討 SurfaceView 與多線程的混搭。之所以要將兩者結合,是為了避免動畫閃爍—
Android 入門:把 HelloWorld 專案的每個細節看明白
每一本 Android 書的第一章幾乎都是 HelloWorld。但多數人跑完就跳過了,其實這個看似空蕩蕩的專案裡,藏著整個 Android 開發架構的縮影。把目錄結構與