<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<Button
android:id="@+id/take_photo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Take Photo"
/>
<ImageView
android:id="@+id/picture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
/>
</LinearLayout>
MainActivity.java
package com.example.choosepictest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
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.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends Activity {
public static final int TAKE_PHOTO=1;
public static final int CROP_PHOTO=2;
private Button takePhoto;
private ImageView picture;
private Uri imageUri;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
takePhoto=(Button)findViewById(R.id.take_photo);
picture=(ImageView)findViewById(R.id.picture);
takePhoto.setOnClickListener(new OnClickListener(){
public void onClick(View v){
//创建File对象,用于存储拍照后的照片
File outputImage=new File(Environment.getExternalStorageDirectory(),"output_image.jpg");
try{
if(outputImage.exists()){
outputImage.delete();
}
outputImage.createNewFile();
}catch(IOException e){
e.printStackTrace();
}
imageUri=Uri.fromFile(outputImage);
Intent intent=new Intent("android.media.action.IMAGE_CAPTURE");
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent,TAKE_PHOTO); //启动相机程序
}
});
}
protected void onActivityResult(int requestCode,int resultCode,Intent data){
switch(requestCode){
case TAKE_PHOTO:
if(resultCode==RESULT_OK)
{
Intent intent=new Intent("com.android.camera.action.CROP");
intent.setDataAndType(imageUri, "image/*");
intent.putExtra("scale", true);
intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
startActivityForResult(intent,CROP_PHOTO); //启动剪裁程序
}
break;
case CROP_PHOTO:
if(resultCode==RESULT_OK){
try{
Bitmap bitmap=BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
picture.setImageBitmap(bitmap); //将剪裁的图片显示出来
}catch(FileNotFoundException e){
e.printStackTrace();
}
}
break;
default:
break;
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}