Android 调用系统相机拍照保存以及调用系统相册的方法
系统已经有的东西,如果我们没有新的需求的话,直接调用是最直接的。下面讲讲调用系统相机拍照并保存图片和如何调用系统相册的方法。
首先看看调用系统相机的核心方法:
Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(camera, CAMERA);
相机返回的数据通过下面的回调方法取得,并处理:
public static final int CAMERA = 0x01;
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(requestCode == CAMERA && resultCode == Activity.RESULT_OK && null != data){ String sdState=Environment.getExternalStorageState(); if(!sdState.equals(Environment.MEDIA_MOUNTED)){ GameLog.log(Tag, "sd card unmount"); return; } new DateFormat(); String name= DateFormat.format("yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA))+".jpg"; Bundle bundle = data.getExtras(); //获取相机返回的数据,并转换为图片格式 Bitmap bitmap = (Bitmap)bundle.get("data"); FileOutputStream fout = null; File file = new File("/sdcard/pintu/"); file.mkdirs(); String filename=file.getPath()+name; try { fout = new FileOutputStream(filename); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fout); } catch (FileNotFoundException e) { e.printStackTrace(); }finally{ try { fout.flush(); fout.close(); } catch (IOException e) { e.printStackTrace(); } } //显示图片 } }
下面是调用系统相册并取得照片的方法:
-
Intent picture = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
-
startActivityForResult(picture, PICTURE);
下面是相应的回调方法:
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(requestCode == CAMERA && resultCode == Activity.RESULT_OK && null != data){ Uri selectedImage = data.getData(); String[] filePathColumns={MediaStore.Images.Media.DATA}; Cursor c = this.getContentResolver().query(selectedImage, filePathColumns, null,null, null); c.moveToFirst(); int columnIndex = c.getColumnIndex(filePathColumns[0]); String picturePath= c.getString(columnIndex); c.close(); //获取图片并显示 }
这样就完成了系统调用,很简单。