拍照和从相册选择图片

时间:2020-12-24 13:30:25
private void chosePhoto() {
DialogUtil.showDoubleNoneTitleTextDialog(activity, "选择图片", "拍照",
"图库", new OnDialogClickListener() {


@Override
public boolean onClick(View v) {
takePicture();
return false;
}
}, new OnDialogClickListener() {


@Override
public boolean onClick(View v) {
openAlbum();
return false;
}
});


}


// 拍照
public void takePicture() {
String state = Environment.getExternalStorageState();
if (state.equals(Environment.MEDIA_MOUNTED)) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File outDir = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
if (!outDir.exists()) {
outDir.mkdirs();
}
File outFile = new File(outDir, System.currentTimeMillis() + ".jpg");
picFileFullName = outFile.getAbsolutePath();
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(outFile));
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
} else {
Log.e(TAG, "请确认已经插入SD卡");
}
}


// 打开本地相册
public void openAlbum() {
Intent intentFromGallery = new Intent();
// 设置文件类型
intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);
intentFromGallery.addCategory(Intent.CATEGORY_OPENABLE);
intentFromGallery.setType("image/*");
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
startActivityForResult(intentFromGallery, SELECT_PIC_KITKAT);
} else {
startActivityForResult(intentFromGallery, CREATE_REQUESTCODE);
}
}


@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_CANCELED) {
return;
}


if (CREATE_REQUESTCODE == requestCode) {
if (null != data) {
Uri uri = data.getData();
if (uri != null) {
String realPath = getRealPathFromURI(uri);
Log.e(TAG, "获取图片成功,path=" + realPath);


setImageView(realPath);
} else {
Log.e(TAG, "从相册获取图片失败");
}
}
} else if (SELECT_PIC_KITKAT == requestCode) {
if (null != data) {
setImageView(FragWeiXiuYuYue.getPath(getActivity(),
data.getData()));
}
}
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == -1) {
Log.e(TAG, "获取图片成功,path=" + picFileFullName);


setImageView(picFileFullName);
} else if (resultCode == 0) {
// 用户取消了图像捕获
} else {
// 图像捕获失败,提示用户
Log.e(TAG, "拍照失败");
}
}
}