今天介紹用最簡單的方式調用其他有相機功能的服務幫我們拍照
這樣可以省去很多不必要的麻煩,簡化應用程式,下面就開始為您介紹
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="@+id/captureimage"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="使用其他服務幫忙拍照 "
/>
<ImageView
android:id="@+id/imagecaptured"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
DemoCameraActivity.java
package jim.demo.camera;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class DemoCameraActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//調用其他服務拍照按鈕
Button buttonCamera = (Button)findViewById(R.id.captureimage);
buttonCamera.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v) {
//使用Intent調用其他服務幫忙拍照
Intent intent_camera = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent_camera, 0);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//拍照後顯示圖片
ImageView iv = (ImageView)findViewById(R.id.imagecaptured);
if (resultCode == RESULT_OK)
{
//取出拍照後回傳資料
Bundle extras = data.getExtras();
//將資料轉換為圖像格式
Bitmap bmp = (Bitmap) extras.get("data");
//載入ImageView
iv.setImageBitmap(bmp);
}
//覆蓋原來的Activity
super.onActivityResult(requestCode, resultCode, data);
}
}
執行後畫面
說明:
使用Intent調用其他服務幫忙拍照主要只有簡單的二行
Intent intent_camera = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent_camera, 0);
第一行是啟用呼叫其他有拍照功能的Intent
第二行是執行呼叫,後面的"0"是參數,可以用來分辨用,下面說明(注)
//拍照後回傳監聽式
protected void onActivityResult(int requestCode, int resultCode, Intent data)
data是照片資料
requestCode是剛剛回傳的參數 = 0(注)
resultCode判別按下的是確定或取消
注:為什麼會有這個參數,主要是因為不管是抓取手機內圖片或是拍照後
都是會回到onActivityResult這個監聽式,如果沒有用這個參數,就分辨不出是用哪個功能
也就沒辦法去接收相關的資料,拍照和抓取手機內圖片的接收方法是不同的
所以如果無法分辨,只用單一種方式接取是會出現錯誤的
後記:
一般如果應用程式要做用拍照功能,需要在AndroidManifest.xml內
授予使用照相機權限,
而使用調用其他服務幫忙拍照不需要加入此權限也能拍照,因為拍照的是其他的服務
所以本身程式不需要加入權限,這是比較特別的地方。




您好,請問我該如何把調用其他服務拍的照片解析度給放大呢?
回覆刪除我看我的寬*高是120*160的 謝謝
請參考Android Image應用(五) - 縮放、指定圖片大小
刪除(http://jim690701.blogspot.tw/2012/08/android-image.html)
重點在照片抓回來後轉為Bitmap,轉為Bitmap後就可以處理(放大、縮小)
所以你只要照片抓回來轉為Bitmap後去參考第5篇的縮放就可以做到你要的要求了
你好
回覆刪除我用你的程式碼執行後 且將它安裝在手機裡
但是按了button後
他卻沒有反應
請問是手機設定問題
(我已經開了usb偵錯模式了)
還是程式碼哪裡需要修改
謝謝