Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

安卓相機調用與照片存檔:Intent 拍照並寫入 SD 卡完整實作

編輯:Android 開發實例

Android 上實作拍照有兩條路。第一條是呼叫系統內建的相機 App,拿到它回傳的圖片資料;第二條是自己用 Camera 類搭配 SurfaceView、Camera.PreviewCallback 等相關類別打造完整相機。第二條的客製彈性高得多,可以做自訂對焦框、浮水印、連拍,但複雜度也高上不少。一般應用只需要第一種。

用 Intent 啟動相機

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

startActivityForResult(intent, 1);

注意這裡用的是 startActivityForResult() 而非 startActivity(),因為你需要拍完之後的結果。使用者按下確認後,系統會回到你的 Activity 並呼叫:

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

寫入 SD 卡前先檢查可用性

String sdStatus = Environment.getExternalStorageState();

if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 檢測sd是否可用

Log.v("TestFile",

"SD card is not avaiable/writeable right now.");

return;

}

這一步不能省。使用者可能沒插卡、卡壞了,或者卡被掛載為唯讀,不檢查就直接寫檔只會收到一個 FileNotFoundException。以下程式碼會把圖片存到「/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();

}

}

bitmap.compress() 的第二個參數是品質,範圍 0 到 100,JPEG 格式下數字越高檔案越大、畫質越好。寫檔時務必在 finally 中關閉串流,否則檔案可能只寫入一部分就因為緩衝區未清空而損壞。

權限設定

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

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

完整 Demo

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)) { // 檢測sd是否可用

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>

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="https://schemas.android.com/apk/res/android"

package="barry.android.c"

android:versionCode="1"

android:versionName="1.0" >

<uses-sdk android:minSdkVersion="7" />

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

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

<application

android:icon="@drawable/ic_launcher"

android:label="@string/app_name" >

<activity

android:label="@string/app_name"

android:name=".MyCaremaActivity" >

<intent-filter >

<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />

</intent-filter>

</activity>

</application>

</manifest>

最後提醒一個實務上的重要限制:透過 data.getExtras().get("data") 取得的 Bitmap 只是縮圖,解析度通常遠低於相機實際拍攝的尺寸,放大後會模糊。若需要原始畫質,正確作法是先在呼叫相機時用 EXTRA_OUTPUT 指定一個目標檔案的 Uri,讓相機直接把原圖寫到該位置,你的程式便完全不經手 Bitmap 物件,也就不會有縮圖與記憶體爆掉的問題。此外在 Android 4.4 以後,直接寫死 /sdcard 路徑已不建議,請改用 Environment.getExternalStorageDirectory() 或 app 專屬目錄。

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