編輯:關於 Android 程式設計
要在自己的 App 裡拍照,最省事的方式是直接呼叫系統相機。但這裡藏著一個很多人栽過的坑:預設拿回來的是縮圖,不是原圖。
按下按鈕後啟動相機,拍照完成於 onActivityResult 中從 data 取出 Bitmap:
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 1);
}
});
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
String sdStatus = Environment.getExternalStorageState();
if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) {
Log.v("TestFile", "SD card is not avaiable/writeable right now.");
return;
}
Bundle bundle = data.getExtras();
Bitmap bitmap = (Bitmap) bundle.get("data"); // 這是縮圖
FileOutputStream b = null;
try {
b = new FileOutputStream(fileName);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try { b.flush(); b.close(); } catch (IOException e) { e.printStackTrace(); }
}
imageView.setImageBitmap(bitmap);
}
}
這個 bitmap 的尺寸通常只有幾十 KB,解析度遠低於實際拍攝的畫面。原因是系統相機為了避開跨行程傳輸大 Bitmap 造成 TransactionTooLargeException,只在 extras 裡塞一張符合 View 尺寸的縮圖。適合只需要頭像、縮圖列表的場景。
要取得原始解析度,就必須在啟動相機時告訴它「把檔案寫到哪裡」,而不是透過 Intent 回傳。
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH.mm.ss");
String name = format.format(new Date());
fileName = "/sdcard/myImage/" + name + ".jpg";
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(fileName)));
startActivityForResult(intent, 1);
}
});
關鍵就是 MediaStore.EXTRA_OUTPUT 這個 extra。設了它之後,相機 App 會把成品寫到該路徑,回傳的 data 就不再帶 bitmap。
on Activity Result 中只負責驗證檔案並載入顯示:
if (resultCode == Activity.RESULT_OK) {
if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
return;
}
// 此時檔案已由相機寫入 fileName
Bitmap bitmap = BitmapFactory.decodeFile(fileName);
imageView.setImageBitmap(bitmap);
}
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/btn_camera"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="拍照" />
<ImageView
android:id="@+id/imageView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignLeft="@+id/btn_camera"
android:layout_below="@+id/btn_camera"
android:layout_marginTop="17dp"
android:background="#999999" />
</RelativeLayout>
原範例在 onCreate 裡用 new File("/sdcard/myImage/").mkdirs() 建目錄,但硬編碼路徑在 Android 4.4 之後就不再可靠。正確作法是呼叫 Environment.getExternalStoragePublicDirectory(DIRECTORY_PICTURES) 取得標準相簿位置,並在 manifest 宣告 WRITE_EXTERNAL_STORAGE;Android 6.0 起還必須在執行期動態申請權限。
其次,Uri.fromFile() 傳給其他 App 會在 Android 7.0 以後觸發 FileUriExposedException。必須改用 FileProvider.getUriForFile() 取得 content:// URI,並在 manifest 中設定對應的 paths 與 grant 權限。
最後,做法二的 on Activity Result 不該再從 extras 取 bitmap,也不該把整張原圖 decode 進記憶體。原圖动辄數 MB,直接 decodeFile 在記憶體受限的裝置上必然 OOM。應改用 BitmapFactory.Options 搭配 inJustDecodeBounds 與 inSampleSize 做降採樣,或使用 ExifInterface 讀取方向資訊後正確旋轉。
Android 數據存儲的五大方式全解與異同對比
數據存儲是開發中使用頻率極高的環節。本文系統梳理 Android 平台實現數據持久化的五種主流方式,並對它們的特點與適用場景做了對比。 第一種:SharedPrefer
手機瀏覽器哪個最省流量?六款主流瀏覽器實測對比
流量一直是筆者最苦惱的問題,總要時時關注自己的流量損耗。可以說中國的手機用戶無疑是全世界最「悲催」的群體之一,時時被高昂的上網費用所牽絆。在流量費用偏高的環境下上網,如何
OkHttp 簡單封裝:打造省心的網絡請求輔助框架
序言 OkHttp 的強大毋庸置疑,幾乎能在網絡層搞定一切。但也正因為功能全面,每構建一個請求都得寫一大堆配置代碼。這裡分享一個對 OkHttp 做了極限封裝的輔助框架,
GreenDAO 3.X 搭配 Volley 與 Gson 的資料儲存實作
GreenDAO 是 Android 上常見的 ORM 方案。相較原生 SQLite,它在使用便利性、效能與程式碼生成方面有明顯優勢。GreenDAO 3.X 之後,主要