标签:
准备工作
权限
<!-- 往SDCard写入数据权限 -->
<uses-permission android:name="android.permission.
WRITE_EXTERNAL_STORAGE" />
<!--请求访问使用照相设备-->
<uses-permission android:name="android.permission.CAMERA" />
常量
public final static int ALBUM_REQUEST_CODE = 1;
public final static int CROP_REQUEST = 2;
public final static int CAMERA_REQUEST_CODE = 3;
// 拍照路径
public static String SAVED_IMAGE_DIR_PATH =
Environment.getExternalStorageDirectory().getPath()
+ "/AppName/camera/";
String cameraPath;
相机
// 指定相机拍摄照片保存地址
String state = Environment.getExternalStorageState();
if (state.equals(Environment.MEDIA_MOUNTED)) {
cameraPath = SAVED_IMAGE_DIR_PATH +
System.currentTimeMillis() + ".png";
Intent intent = new Intent();
// 指定开启系统相机的Action
intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
String out_file_path = SAVED_IMAGE_DIR_PATH;
File dir = new File(out_file_path); if (!dir.exists()) {
dir.mkdirs();
}
// 把文件地址转换成Uri格式
Uri uri = Uri.fromFile(new File(cameraPath));
// 设置系统相机拍摄照片完成后图片文件的存放地址
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(intent, CAMERA_REQUEST_CODE);
} else {
Toast.makeText(getApplicationContext(), "请确认已经插入SD卡",
Toast.LENGTH_LONG).show();
}
onActivityResult
拿到cameraPath,就随便你搞了。
@Override
public void onActivityResult(int requestCode,
int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == CAMERA_REQUEST_CODE) {
LogUtil.d("path=" + cameraPath);
}
}
相册
Intent intent = new Intent(Intent.ACTION_PICK, null);
intent.setDataAndType(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, ALBUM_REQUEST_CODE);
onActivityResult
调用系统相册,然后通过Uri拿到图片的绝对地址。
@Override
public void onActivityResult(int requestCode,
int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == AppConstants.ALBUM_REQUEST_CODE) {
try {
Uri uri = data.getData();
final String absolutePath=
getAbsolutePath(mActivity, uri);
ogUtil.d("path=" + absolutePath);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
getAbsolutePath方法
public String getAbsolutePath(final Context context,
final Uri uri) {
if (null == uri) return null;
final String scheme = uri.getScheme();
String data = null;
if (scheme == null)
data = uri.getPath();
else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
data = uri.getPath();
} else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
Cursor cursor = context.getContentResolver().query(uri,
new String[]{MediaStore.Images.ImageColumns.DATA},
null, null, null);
if (null != cursor) {
if (cursor.moveToFirst()) {
int index = cursor.getColumnIndex(
MediaStore.Images.ImageColumns.DATA);
if (index > -1) {
data = cursor.getString(index);
}
}
cursor.close();
}
} return data;
}
标签:
原文地址:http://www.cnblogs.com/GeChuangGuang/p/5500722.html