调用系统相机拍照:
intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, RESULT_CAMARA_IMAGE); // RESULT_CAMARA_IMAGE:Activity的标志。自已定义
调用系统相册:
intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, RESULT_LOAD_IMAGE); // RESULT_LOAD_IMAGE:Activity的标志。自已定义
下面是在onActivityResult()中调用的两个方法:
/**
* 调用系统相册的操作,在onActivityResult中调用
*
* @param data
* onActivityResult中的Intent
*/
public Bitmap map(Intent data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = mContext.getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
Log.d("picturePath", picturePath);
return BitmapFactory.decodeFile(picturePath);
}
/**
* 调用系统相机,在onActivityResult中调用,拍照后保存到sdcard卡中
*
* @param data
* onActivityResult中的Intent
* @return
*/
public Bitmap camara(Intent data) {
String sdStatus = Environment.getExternalStorageState();
if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
Log.i("TestFile", "SD card is not avaiable/writeable right now.");
Toast.makeText(mContext,
"SD card is not avaiable/writeable right now.",
Toast.LENGTH_LONG).show();
return null;
}
String name = new DateFormat().format("yyyyMMdd_hhmmss",
Calendar.getInstance(Locale.CHINA))
+ ".jpg";
Bundle bundle = data.getExtras();
Bitmap bitmap = (Bitmap) bundle.get("data");
FileOutputStream b = null;
File file = new File("sdcard/DCIM/Camera/");
file.mkdirs();// 创建文件夹
String fileName = "sdcard/DCIM/Camera/" + name;
try {
b = new FileOutputStream(fileName);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
b.flush();
b.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return bitmap;
}