Android调用系统相机和文件浏览器

时间:2023-12-28 16:54:17

//拍照功能,调用系统的相机功能

Intent intent2 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent2, 1);

获取拍照的图像

protected void onActivityResult(int requestCode, int resultCode, Intent data) 

{

try
{
  Bitmap bitmap = (Bitmap)data.getExtras().get("data");
  personImg.setImageBitmap(CircleImage(bitmap));
  File file=new File(Environment.getExternalStorageDirectory().getAbsolutePath());
  FileOutputStream out=new FileOutputStream(file.getAbsolutePath()+"/person.jpg");
  //保存图片
  bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out); } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.onActivityResult(requestCode, resultCode, data);
}

调用系统文件浏览器

Intent intent=new Intent();
//制定内容的类型为图像
intent.setType("image/*");
//制定调用系统内容的action
intent.setAction(Intent.ACTION_GET_CONTENT);
//显示系统相册
startActivityForResult(intent, 0);

获取选择的内容

protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
try {
Uri uri=data.getData();
//获取封装相册图像的数据
Cursor cursor=getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
//获取选中相册的文件路径
String filePath=cursor.getString(1);
cursor.close();
//创建bitmap对象
Bitmap map=BitmapFactory.decodeFile(filePath);
File file=new File("/sdcard/img.jpg");
FileOutputStream out=new FileOutputStream(file);
//保存图片
map.compress(Bitmap.CompressFormat.JPEG, 100, out);
} catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} }