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

Android 相機調用與將照片儲存到 SD 卡實例

編輯:關於 Android 開發

在 Android 中實作拍照有兩種方式:一是呼叫系統自帶的相機並使用其回傳的照片資料;二是自行以 Camera 類別實作相機功能,後者定制度高但也較複雜。一般應用只需使用第一種即可。本文以完整範例示範呼叫系統相機、顯示照片並存入 SD 卡。

一、以 Intent 啟動相機

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 1);

拍完照後,可在 onActivityResult 中取得 Bitmap 物件:

Bitmap bitmap = (Bitmap) data.getExtras().get("data");

二、檢查 SD 卡並寫入檔案

寫入 SD 卡前最好先確認其可用性:

String sdStatus = Environment.getExternalStorageState();
if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 檢測 SD 是否可用
    Log.v("TestFile", "SD card is not avaiable/writeable right now.");
    return;
}

將圖像存到「sdcard/myImage/111.jpg」:

File file = new File("/sdcard/myImage/");
file.mkdirs(); // 建立資料夾
String fileName = "/sdcard/myImage/111.jpg";
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();
    }
}

別忘了在 Manifest 中設定讀寫 SD 卡的權限:

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

三、完整範例 MyCaremaActivity.java

package barry.android.c;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
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;

public class MyCaremaActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button button = (Button) findViewById(R.id.button);
        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"); // 取得相機回傳資料並轉為 Bitmap
            FileOutputStream b = null;
            File file = new File("/sdcard/myImage/");
            file.mkdirs(); // 建立資料夾
            String fileName = "/sdcard/myImage/111.jpg";
            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) findViewById(R.id.imageView)).setImageBitmap(bitmap); // 顯示於 ImageView
        }
    }
}

四、版面配置 main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <Button
        android:id="@+id/button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="點擊啟動相機" />
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="#999999" />
</LinearLayout>

透過 MediaStore.ACTION_IMAGE_CAPTURE 呼叫系統相機,在 onActivityResult 中取得 Bitmap,再以 Bitmap.compress 壓縮寫入檔案,即可完整實作拍照、顯示與儲存的功能。

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