編輯:關於 Android 程式設計
這看似是個簡單需求,卻經常遇到。做 Android 開發時,我們往往不能直接在原檔上動手——想要壓縮圖片、加上浮水印或做任何後處理,都得先複製一份出來。最近正好在做圖片相關的專案,就把這段做法整理出來分享。
整個流程分兩步:
private void string2File() {
tempFiles = new File[resultFileList.size()];
passFileMap = new HashMap<String, File>();
for (int i = 0; i < resultFileList.size(); ++i) {
// 取出原檔名
String name = resultFileList.get(i)
.substring(resultFileList.get(i).lastIndexOf("/") + 1);
// 改存到應用的快取目錄
name = getCacheDir(mContext) + "/" + name;
File file = new File(resultFileList.get(i));
tempFiles[i] = new File(name);
Uri uri = Uri.fromFile(tempFiles[i]);
try {
// 邊解碼邊縮放,避免大圖 OOM
Bitmap bitmap = decodeFile(file, 1000);
if (!tempFiles[i].exists()) {
tempFiles[i].createNewFile();
}
FileOutputStream out = new FileOutputStream(tempFiles[i]);
bitmap.compress(Bitmap.CompressFormat.JPEG, 60, out);
out.flush();
out.close();
passFileMap.put(tempFiles[i].getAbsolutePath(), tempFiles[i]);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/** 解碼圖片並依目標尺寸等比縮小 */
private Bitmap decodeFile(File f, int bmpsize) {
if (f == null || !f.exists()) return null;
try {
// 第一趟:只讀尺寸,不載入像素
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
o.inPreferredConfig = Bitmap.Config.ARGB_8888;
o.inInputShareable = true;
o.inPurgeable = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
final int REQUIRED_SIZE = bmpsize;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
if (width_tmp > REQUIRED_SIZE || height_tmp > REQUIRED_SIZE) {
if (width_tmp > height_tmp) {
scale = width_tmp / REQUIRED_SIZE;
} else {
scale = height_tmp / REQUIRED_SIZE;
}
}
// 第二趟:以 inSampleSize 實際解碼
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
o2.inPreferredConfig = Bitmap.Config.ARGB_8888;
o2.inInputShareable = true;
o2.inPurgeable = true;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
1. 兩趟解碼法
這段程式最值得學的不是「複製檔案」,而是 decodeFile() 裡的兩趟解碼技巧。第一趟設 inJustDecodeBounds = true,BitmapFactory 只讀取圖片尺寸而不真正配置像素記憶體;算出縮放比例後,第二趟再用 inSampleSize 實際解碼。這是處理手機大尺寸照片時避免 OOM 的標準做法。
2. 存到快取目錄
範例把結果寫進 getCacheDir(),而不是外部儲存空間。這樣做的好處是不需要額外申請儲存權限,也不會在使用者相簿裡留下垃圾檔案;代價是系統空間不足時可能會清除這些檔案,因此適合放「可重新產生的中間結果」,不能當作長期存放位置。
這種「先複製再處理」的模式,在本機圖片壓縮的場景裡非常常見。另外提醒兩點:bitmap.compress() 之後記得 recycle 不再使用的 Bitmap,串流也要確實關閉;若要批次處理大量檔案,建議放到背景執行緒,避免卡住主執行緒。
Android N 通知新體驗:桌面未讀提示與 MessagingService
Android N 的通知系統更強調互動與情境整合。透過 MessagingService,開發者可以建立類似訊息應用程式的通知體驗,讓使用者不必進入 App 就能閱讀、
Android 內存優化完全指南:從內存管理機制到告別 OOM 的實踐總結
內存優化是 Android 性能優化中最關鍵的一環,而避免 OOM(Out Of Memory)更是其中的核心。本文系統性地梳理了 Android 的內存管理機制、OOM
Android 學習教程之日曆控件使用
日曆控件常用於日期選擇、活動報名、行事提醒等情境。Android 中可透過自訂 View 或第三方庫實作月曆畫面。以下以 CalendarPickerView 為例,整理
Android UI 設計之十:自訂 FlexibleListView,打造 QQ 空間式阻尼下拉與漸變菜單欄
需求場景:像 QQ 空間一樣自然的下拉體驗在許多社交類 App 中,頂部菜單欄並非永遠不透明,而是會隨著內容滾動逐漸浮現;當使用者回到頂部並繼續下拉時,頭部區域會出現柔軟