這兩種不一樣嗎?其實是一樣的,差別在於取得圖片後的資料流不一樣
處理的方式也不同,因此把它分開成兩篇來介紹,其實寫法是可以寫在一起的
因為拍照和從手機內取得圖檔在取得圖片後都是會回到onActivityResult內的
下面開始來看看怎麼做吧。
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)
{
switch (requestCode) {
case 0:
//取出拍照後回傳資料
Bundle extras = data.getExtras();
//將資料轉換為圖像格式
Bitmap bmp = (Bitmap) extras.get("data");
//如果有資料就丟doCropPhoto進行裁剪
if(bmp!=null){
doCropPhoto(bmp);
}
break;
case 1:
Bitmap photo1 = data.getParcelableExtra("data");
//載入ImageView
iv.setImageBitmap(photo1);
break;
}
}
//覆蓋原來的Activity
super.onActivityResult(requestCode, resultCode, data);
}
protected void doCropPhoto(Bitmap data){
//進行照片裁剪
Intent intent = getCropImageIntent(data);
startActivityForResult(intent, 1);
}
public static Intent getCropImageIntent(Bitmap data) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("image/*");
intent.putExtra("data", data);
intent.putExtra("crop", "true");// crop=true 有這句才能叫出裁剪頁面.
intent.putExtra("aspectX", 1);// 这兩項為裁剪框的比例.
intent.putExtra("aspectY", 1);// x:y=1:1
intent.putExtra("outputX", 300);//回傳照片比例X
intent.putExtra("outputY", 300);//回傳照片比例Y
intent.putExtra("return-data", true);
return intent;
}
}
執行後畫面
看完程式碼應該就可以看出其實大同小異,主要都是用intent.putExtra("crop", "true")
叫出裁剪頁面進行裁剪,不同在拍照後圖檔的不同,所以需要進行不同的轉換
我在使用上其實是會把從手機內取得圖檔和拍照放在一起供使用者選擇,此處是因為介紹
所以把它分開,小弟我就介紹到這裡,有問題請留言或來信,感謝。




沒有留言:
張貼留言
您的寶貴建議是我前進的動力!