做上傳圖片功能時,最常卡住的兩個環節是:如何拿到所選圖片的路徑,以及如何在送出前把圖片壓縮。以下把整個流程記錄下來。
Android 已內建挑選圖片的 Intent,不必自己實作列表:
Intent intent = new Intent(Intent.ACTION_PICK, null);
intent.setDataAndType(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, // 系統中所有圖片
"image/*"); // image/* 代表所有圖片類型
startActivityForResult(intent, PHOTO_GALLERY);
Android 1.5 之後,系統會由 MediaScanner 服務在背景掃描歌曲、圖片、影片等媒體資訊,並把索引寫入 MediaStore.Images.Thumbnails 與 MediaStore.Video.Thumbnails 兩張表。因此我們可以用 managedQuery() 向內容提供者查詢:
Activity.managedQuery(uri, projection, selection, selectionArgs, sortOrder)
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PHOTO_GALLERY:
{
// 只需要圖片路徑欄位
String[] proj = { MediaStore.Images.Media.DATA };
@SuppressWarnings("deprecation")
Cursor cursor = managedQuery(data.getData(), proj, null, null, null);
int photocolumn = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst(); // 游標移到第一筆
String path = cursor.getString(photocolumn); // 取得圖片路徑
break;
}
default:
break;
}
}
思路是先以 inSampleSize 縮小取樣,避免大圖直接解碼造成記憶體溢出;再用 compress() 逐步降低品質,直到檔案小於目標值。
// 將所選圖片轉為串流,path 為上一步取得的路徑
FileInputStream is = new FileInputStream(path);
// 壓縮後要輸出的檔案
File f = new File("圖片保存路徑", "圖片名稱");
int size = 2;
Options options = new Options();
options.inSampleSize = size; // 縮小為原來的 1/size
Bitmap image = BitmapFactory.decodeStream(is, null, options);
is.close();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos); // 100 表示不壓縮
int per = 100;
while (baos.toByteArray().length / 1024 > 500) { // 超過 500KB 就繼續壓
baos.reset(); // 清空緩衝區
image.compress(Bitmap.CompressFormat.JPEG, per, baos);
per -= 10; // 每次遞減 10
}
// 回收圖片、釋放記憶體
if (image != null && !image.isRecycled()) {
image.recycle();
image = null;
System.gc();
}
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
FileOutputStream os = new FileOutputStream(f);
StreamTransferUtils.CopyStream(isBm, os); // 自訂工具類:串流複製
isBm.close();
os.close();
執行完畢後,到指定路徑就能看到壓縮後的圖片。
實務上可再補充兩點:一是 inSampleSize 通常取 2 的次方效果較佳;二是回收 Bitmap 與呼叫 System.gc() 在新版 Android 上已非必要,反而可能拖慢效能,現行做法更傾向直接使用 Glide、Coil 等影像載入庫來處理取樣與快取。