Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 拍照後顯示照片:Intent、檔案輸出路徑與 BitmapFactory

編輯:關於 Android 程式設計

在 Android 中呼叫相機拍照後,若希望自訂照片儲存位置並在拍攝完成後顯示,可以透過 Intent 指定輸出檔案,再於 onActivityResult 中讀取圖片。

拍照流程

按下按鈕時,建立影像擷取 Intent,並透過 MediaStore.EXTRA_OUTPUT 指定照片要儲存的位置:

Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
mPhotoPath = Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + getPhotoFileName();
mPhotoFile = new File(mPhotoPath);
if (!mPhotoFile.exists()) {
    mPhotoFile.createNewFile();
}
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(mPhotoFile));
startActivityForResult(intent, CAMERA_RESULT);

檔名可利用時間戳產生,例如 IMG_年月日_時分秒.jpg,如此一來每次拍照都能保留獨立檔案,也方便後續管理。

拍攝完成後顯示照片

在 onActivityResult 中,若 requestCode 等於拍照請求碼,就能透過 BitmapFactory.decodeFile 讀取剛剛拍好的照片:

if (requestCode == CAMERA_RESULT) {
    Bitmap bitmap = BitmapFactory.decodeFile(mPhotoPath);
    mImageView.setImageBitmap(bitmap);
}

版面配置

畫面可簡單配置一個拍攝按鈕與一個 ImageView:

<Button
    android:id="@+id/button"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="點擊按鈕拍照" />

<ImageView
    android:id="@+id/imageView"
    android:layout_below="@id/button"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" />

權限提醒

若應用需要拍照與寫入外部儲存空間,記得加入相應權限:

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

在較新的 Android 版本中,若涉及敏感資源,還可能需要處理執行期權限請求。完成這些設定後,就能穩定完成拍照、存檔與預覽流程。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved