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

Android 實作:從相冊選圖與呼叫系統拍照

編輯:關於 Android 程式設計

開發時幾乎一定會碰到「新增圖片」的需求。取得圖片有兩條路:從本機相冊挑選,或呼叫相機即時拍攝。兩者的實作方式其實是同一套邏輯——用 startActivityForResult() 出發,用 onActivityResult() 收結果。

(呼叫相機又可分為「叫用系統相機」與「自訂相機畫面」兩種,本文只談前者。)

一、從相冊選圖

出發:開啟系統圖庫

Intent intent = new Intent();
intent.setType("image/*");                    // 限定只選圖片
intent.setAction(Intent.ACTION_GET_CONTENT);  // 由系統挑一個能處理的 App
startActivityForResult(intent, LOCAL_IMAGE_CODE);

回程:取得 Uri 並解成 Bitmap

Uri uri = data.getData();

// 從 content:// 形式的 Uri 中取出真實路徑
url = uri.toString().substring(uri.toString().indexOf("///") + 2);

if (url.contains(".jpg") && url.contains(".png")) {
    Toast.makeText(this, "請選擇圖片", Toast.LENGTH_SHORT).show();
    return;
}

bitmap = HelpUtil.getBitmapByUrl(url);

二、呼叫系統拍照

出發:指定輸出路徑後啟動相機

String fileName = "IMG_" + curFormatDateStr + ".png";

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

// 關鍵:告訴相機把照片存到哪裡
intent.putExtra(MediaStore.EXTRA_OUTPUT,
                Uri.fromFile(new File(rootUrl, fileName)));
intent.putExtra("fileName", fileName);

startActivityForResult(intent, CAMERA_IMAGE_CODE);

回程:讀取並修正方向

url = rootUrl + "/" + "IMG_" + curFormatDateStr + ".png";
bitmap = HelpUtil.getBitmapByUrl(url);
showImageIv.setImageBitmap(HelpUtil.createRotateBitmap(bitmap));

為什麼需要旋轉?多數手機的感光元件是橫向擺放,照片會伴隨 EXIF 方向資訊;部分機型在透過 Intent 產檔時沒有把這個資訊正確寫入,導致 ImageView 顯示時圖片逆時針躺倒 90 度。手動補一次順時針旋轉即可:

/**
 * 將 bitmap 順時針旋轉 90 度
 * @param bitmap 原圖
 * @return 旋轉後的新 bitmap
 */
public static Bitmap createRotateBitmap(Bitmap bitmap) {
    if (bitmap != null) {
        Matrix m = new Matrix();
        try {
            m.setRotate(90, bitmap.getWidth() / 2, bitmap.getHeight() / 2);
            Bitmap bmp2 = Bitmap.createBitmap(bitmap, 0, 0,
                    bitmap.getWidth(), bitmap.getHeight(), m, true);
            bitmap.recycle();     // 舊圖已無用,主動釋放
            bitmap = bmp2;
        } catch (Exception ex) {
            System.out.print("創建圖片失敗!" + ex);
        }
    }
    return bitmap;
}

更嚴謹的做法是讀取 EXIF 中的 Orientation 標籤再決定旋轉角度,而不是無條件轉 90 度——否則在方向資訊本來就正確的機型上,反而會把圖轉歪。

三、完整範例

1. 執行畫面

2. res/layout/activity_main.xml

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:id="@+id/id_insert_btns_ll"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:orientation="horizontal">

        <Button
            android:id="@+id/id_local_img_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="插入本地圖片" />

        <Button
            android:id="@+id/id_camera_img_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="插入拍照圖片" />
    </LinearLayout>

    <TextView
        android:id="@+id/id_show_url_tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:gravity="center"
        android:textColor="#FF0000"
        android:text="顯示圖片路徑" />

    <ImageView
        android:id="@+id/id_image_iv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/id_insert_btns_ll"
        android:layout_above="@id/id_show_url_tv"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

3. MainActivity.java

package com.example.insertimagedemo;

import java.io.File;
import java.util.Calendar;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

    private static final int LOCAL_IMAGE_CODE  = 1;
    private static final int CAMERA_IMAGE_CODE = 2;
    private static final String IMAGE_TYPE     = "image/*";

    private String rootUrl = null;
    private String curFormatDateStr = null;

    private Button localImgBtn, cameraImgBtn;
    private TextView showUrlTv;
    private ImageView showImageIv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findById();
        initData();
    }

    /** 初始化 view */
    private void findById() {
        localImgBtn  = (Button)  this.findViewById(R.id.id_local_img_btn);
        cameraImgBtn = (Button)  this.findViewById(R.id.id_camera_img_btn);
        showUrlTv    = (TextView) this.findViewById(R.id.id_show_url_tv);
        showImageIv  = (ImageView) this.findViewById(R.id.id_image_iv);

        localImgBtn.setOnClickListener(this);
        cameraImgBtn.setOnClickListener(this);
    }

    /** 初始化相關資料:以外部儲存根目錄作為拍照存檔位置 */
    private void initData() {
        rootUrl = Environment.getExternalStorageDirectory().getPath();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.id_local_img_btn:
                processLocal();
                break;
            case R.id.id_camera_img_btn:
                processCamera();
                break;
        }
    }

    /** 處理「本地圖片」按鈕 */
    private void processLocal() {
        Intent intent = new Intent();
        intent.setType(IMAGE_TYPE);
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent, LOCAL_IMAGE_CODE);
    }

    /** 處理「拍照」按鈕 */
    private void processCamera() {
        curFormatDateStr = HelpUtil.getDateFormatString(
                Calendar.getInstance().getTime());

        String fileName = "IMG_" + curFormatDateStr + ".png";
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT,
                Uri.fromFile(new File(rootUrl, fileName)));
        intent.putExtra("fileName", fileName);
        startActivityForResult(intent, CAMERA_IMAGE_CODE);
    }

    /** 處理跳轉後的返回結果 */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            String url = "";
            Bitmap bitmap = null;

            if (requestCode == LOCAL_IMAGE_CODE) {
                Uri uri = data.getData();
                url = uri.toString().substring(uri.toString().indexOf("///") + 2);
                Log.e("uri", uri.toString());

                if (url.contains(".jpg") && url.contains(".png")) {
                    Toast.makeText(this, "請選擇圖片", Toast.LENGTH_SHORT).show();
                    return;
                }

                bitmap = HelpUtil.getBitmapByUrl(url);
                showImageIv.setImageBitmap(bitmap);

            } else if (requestCode == CAMERA_IMAGE_CODE) {
                url = rootUrl + "/" + "IMG_" + curFormatDateStr + ".png";
                bitmap = HelpUtil.getBitmapByUrl(url);
                showImageIv.setImageBitmap(HelpUtil.createRotateBitmap(bitmap));
            }

            showUrlTv.setText(url);

        } else {
            Toast.makeText(this, "沒有添加圖片", Toast.LENGTH_SHORT).show();
        }
    }
}

4. HelpUtil.java

package com.example.insertimagedemo;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.annotation.SuppressLint;
import android.content.ContentResolver;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;

public class HelpUtil {

    /** 依圖片路徑取得本機圖片的 Bitmap */
    public static Bitmap getBitmapByUrl(String url) {
        FileInputStream fis = null;
        Bitmap bitmap = null;
        try {
            fis = new FileInputStream(url);
            bitmap = BitmapFactory.decodeStream(fis);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            bitmap = null;
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                fis = null;
            }
        }
        return bitmap;
    }

    /** 透過 ContentResolver 由 Uri 直接解圖(另一種做法) */
    public static Bitmap getBitmapByUri(Uri uri, ContentResolver cr) {
        Bitmap bitmap = null;
        try {
            bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            bitmap = null;
        }
        return bitmap;
    }

    /** bitmap 順時針旋轉 90 度 */
    public static Bitmap createRotateBitmap(Bitmap bitmap) {
        if (bitmap != null) {
            Matrix m = new Matrix();
            try {
                m.setRotate(90, bitmap.getWidth() / 2, bitmap.getHeight() / 2);
                Bitmap bmp2 = Bitmap.createBitmap(bitmap, 0, 0,
                        bitmap.getWidth(), bitmap.getHeight(), m, true);
                bitmap.recycle();
                bitmap = bmp2;
            } catch (Exception ex) {
                System.out.print("創建圖片失敗!" + ex);
            }
        }
        return bitmap;
    }

    /** 取得格式化日期字串,用於產生檔名 */
    @SuppressLint("SimpleDateFormat")
    public static String getDateFormatString(Date date) {
        if (date == null) {
            date = new Date();
        }
        SimpleDateFormat matter = new SimpleDateFormat("yyyyMMdd_HHmmss");
        return matter.format(date);
    }
}

四、實務上必須修正的幾處

上面這份程式碼邏輯清楚、適合入門,但直接搬到現今的專案會遇到問題,列在這裡供對照:

1. Uri.fromFile() 在 Android 7.0 以上會崩潰
系統從 Nougat 起禁止把 file:// 型別的 Uri 傳給其他 App,會拋 FileUriExposedException。正確做法是用 FileProvider:

// res/xml/file_paths.xml
<paths>
    <external-path name="my_images" path="Android/data/com.example.insertimagedemo/files/Pictures" />
</paths>

// Manifest
<provider
    android:name="androidx.core.content.FileProvider"
    android:authorities="com.example.insertimagedemo.fileprovider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider>

// 使用
Uri photoUri = FileProvider.getUriForFile(this,
        "com.example.insertimagedemo.fileprovider", file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);

2. 從 content:// Uri 取「真實路徑」不可靠
程式裡那句 uri.toString().substring(indexOf("///") + 2) 在舊版 Gallery 上還能勉強運作,但 ContentProvider 的路徑形式各家不同,到了 Android 4.4(KitKat)之後,ACTION_GET_CONTENT 回傳的常是 content://com.android.providers.media.documents/document/image%3A1234 這類 document Uri,根本沒有對應的檔案路徑。正確做法是直接用 ContentResolver 開串流:

InputStream is = getContentResolver().openInputStream(data.getData());
Bitmap bmp = BitmapFactory.decodeStream(is);

3. 檔名判斷的邏輯有誤
if (url.contains(".jpg") && url.contains(".png")) 用 AND 判斷,意思是「路徑中同時含有 .jpg 和 .png」才擋下——幾乎永遠不成立,等於沒擋。應該用 || 或更好的做法是直接檢查 MIME type。

4. 直接 decode 原圖會 OOM
現代手機照片动辄 4000×3000、十幾 MB,BitmapFactory.decodeStream() 不加降採樣幾乎必然 OutOfMemoryError。至少要用 BitmapFactory.Options 做兩段式解碼:

BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, opts);      // 只讀尺寸,不配置記憶體

int sample = 1;
while (opts.outWidth / (sample * 2) > 1024) {    // 目標約 1024px
    sample *= 2;
}

opts.inSampleSize = sample;
opts.inJustDecodeBounds = false;
Bitmap bmp = BitmapFactory.decodeStream(is, null, opts);

更省事的做法是交給 Glide 或 Coil 這類圖片框架處理。

5. 權限與新的選圖 API
讀取外部儲存空間需要執行期動態申請 READ_EXTERNAL_STORAGE(Android 13 以上還要細分為 READ_MEDIA_IMAGES)。而如果目的只是「選一張圖來用」,其實完全不需要任何儲存空間權限——改用 ActivityResultContracts.GetContent() 或 Photo Picker,由系統在授權範圍內暫時把 URI 交給你,這是現在的推薦做法:

private final ActivityResultLauncher<String> pickImage =
        registerForActivityResult(new ActivityResultContracts.GetContent(), uri -> {
            if (uri != null) {
                // 直接用 uri 讀串流,不需要路徑、不需要權限
            }
        });

// 觸發
pickImage.launch("image/*");
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved