1. 程式人生 > >Android-開啟系統相機並拍照兩種顯示方式。

Android-開啟系統相機並拍照兩種顯示方式。

目標效果:

    

第二張為點選第一個按鈕拍照後顯示的,比較模糊,第三章為點選第二個按鈕拍照後顯示的,比較清楚。

1.activity_main.xml頁面設定佈局。

activity_main.xml頁面:

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

    <Button
        android:id="@+id/btnOpenCamera"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="拍照立即顯示" />
    <Button
        android:id="@+id/btnSavePhoto"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="60dp"
        android:text="拍照儲存後顯示" />
    
    <ImageView
        android:id="@+id/ivShowPicture"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="130dp" />
</RelativeLayout>
2.MainActivity.java頁面開啟相機並獲取傳遞回來的資料,兩種方式第一個比較模糊,適合小圖,第二個清楚些。 MainActivity.java頁面:
package com.example.camera;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URI;

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

public class MainActivity extends Activity implements OnClickListener {

	private Button btnOpenCamera, btnSavePhoto;
	private ImageView ivShowPicture;
	private static int REQUEST_CAMERA_1 = 1;
	private static int REQUEST_CAMERA_2 = 2;
	private String mFilePath;

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

		// 初始化控制元件
		init();

		// 控制元件繫結點選事件
		bindClick();
	}

	// 初始化控制元件和變數
	private void init() {
		btnOpenCamera = (Button) findViewById(R.id.btnOpenCamera);
		btnSavePhoto = (Button) findViewById(R.id.btnSavePhoto);
		ivShowPicture = (ImageView) findViewById(R.id.ivShowPicture);
		mFilePath = Environment.getExternalStorageDirectory().getPath();// 獲取SD卡路徑
		mFilePath = mFilePath + "/" + "temp.png";// 指定路徑
	}

	// 控制元件繫結點選事件
	private void bindClick() {
		btnOpenCamera.setOnClickListener(this);
		btnSavePhoto.setOnClickListener(this);
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.btnOpenCamera:
			// 拍照並顯示圖片
			openCamera_1();
			break;
		case R.id.btnSavePhoto:
			// 拍照後儲存並顯示圖片
			openCamera_2();
			break;
		default:
			break;
		}
	}

	// 拍照並顯示圖片
	private void openCamera_1() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// 啟動系統相機
		startActivityForResult(intent, REQUEST_CAMERA_1);
	}

	// 拍照後儲存並顯示圖片
	private void openCamera_2() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// 啟動系統相機
		Uri photoUri = Uri.fromFile(new File(mFilePath)); // 傳遞路徑
		intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);// 更改系統預設儲存路徑
		startActivityForResult(intent, REQUEST_CAMERA_2);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) { // 如果返回資料
			if (requestCode == REQUEST_CAMERA_1) { // 判斷請求碼是否為REQUEST_CAMERA,如果是代表是這個頁面傳過去的,需要進行獲取
				Bundle bundle = data.getExtras(); // 從data中取出傳遞回來縮圖的資訊,圖片質量差,適合傳遞小圖片
				Bitmap bitmap = (Bitmap) bundle.get("data"); // 將data中的資訊流解析為Bitmap型別
				ivShowPicture.setImageBitmap(bitmap);// 顯示圖片
			} else if (requestCode == REQUEST_CAMERA_2) {
				FileInputStream fis = null;
				try {
					fis = new FileInputStream(mFilePath); // 根據路徑獲取資料
					Bitmap bitmap = BitmapFactory.decodeStream(fis);
					ivShowPicture.setImageBitmap(bitmap);// 顯示圖片
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} finally {
					try {
						fis.close();// 關閉流
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
	}
}
3.因為開啟的是系統相機,所以不需要新增開啟相機的許可權,如果想要在別的應用裡選擇開啟系統相機時也出現你的應用,需要在AndroidManifest.xml頁面進行設定。 AndroidManifest.xml頁面:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.camera"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="17"
        android:targetSdkVersion="19" />

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.camera.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <!-- 註冊相機功能,在別的程式Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);進行啟動相機時也會選擇是否啟動該應用 -->
            <intent-filter>
                <action android:name="android.media.action.IMAGE_CAPTURE" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>

</manifest>
4.執行就可以顯示目標效果了。