方式一:
public class MainActivity extends Activity implements OnClickListener {
private Button button;
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button1);
imageView = (ImageView) findViewById(R.id.imageView1);
button.setOnClickListener(MainActivity.this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
// 根据指定的action跳转到相对应的相机activity
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// 进行跳转并传递过去一个请求码,(在系统相机对应的activity页面同时会返回一个响应码)
startActivityForResult(intent, 1000);
break;
}
}
/**
* 方式一: 1.跳转至系统相机app:Intent intent = new
* Intent(MediaStore.ACTION_IMAGE_CAPTURE); 2.使用系统相机进行拍照
* 3.接收系统相机的返回数据:Bitmap bitmap = (Bitmap) data.getExtras().get("data");
*
*
* */
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1000) {
/*
* 在相机对应的activity页面有这样的操作,所以才能拿到照片
* Intent intent = new Intent();
* intent.putExtra("data", "这里面放的是照片");
*/
if (data != null) {
// 获取拍摄好的照片
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(bitmap);
}
}
}
方式二:
public class MainActivity extends Activity implements OnClickListener {
private Button button;
private ImageView imageView;
private File file;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(MainActivity.this);
imageView = (ImageView) findViewById(R.id.imageView1);
}
public void onClick(View v) {
// 创建意图,跳转到系统相机对应的activity
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// 创建图片的保存路径
String path = Environment.getExternalStorageDirectory()
.getAbsolutePath();
file = new File(path, "guo.jpg");
// 告诉相机照片的存放位置
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(intent, 1000);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1000) {
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
imageView.setImageBitmap(bitmap);
}
}