1 回答
TA贡献1909条经验 获得超7个赞
我假设您想从拍摄的照片中获取 URI。为了从图库和相机中选择图像,您可以尝试这种方式:
1)这种从图库中挑选图像的方法
private void pickFromGallery(int galleryCode) {
URI_REQUEST_CODE = galleryCode;
Intent intent;
if (Build.VERSION.SDK_INT < 19) {
intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, GALLERY_REQUEST_CODE);
} else {
intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, GALLERY_REQUEST_CODE);
}
}
2)这种获取相机拍摄图像的方法(一定要用你的包名替换“com.your.package.name”)
//declare a global variable in your scope to provide the URI of image taken with camera
private URI uri;
private void dispatchTakePictureIntent(int captureCode) {
URI_REQUEST_CODE = captureCode;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
ex.printStackTrace();
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.your.package.name",
photoFile);
uri = photoURI;
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
3)构建onActivityResult方法
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// Result code is RESULT_OK only if the user selects an Image
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == GALLERY_REQUEST_CODE) {
if (URI_REQUEST_CODE == 1) {
Uri selectedImage = data.getData();
if (selectedImage != null) {
Toast.makeText(this, selectedImage.toString(), Toast.LENGTH_SHORT).show();
Log.i("UriFromGalleryPicture", "onActivityResult: " + selectedImage.toString());
}
} else if (URI_REQUEST_CODE == 2) {
if (checkPermissionREAD_EXTERNAL_STORAGE(this)) {
Toast.makeText(this, uri.toString(), Toast.LENGTH_SHORT).show();
Log.i("UriFromCameraPicture", "onActivityResult: " + uri);
}
}
4) 在需要图像 URI 的地方调用 pickFromGallery(1) / dispatchTakePictureIntent(2) 方法
让我们知道这是否有帮助,您应该在问题中详细添加您遇到的错误,以及为图像生成的路径
添加回答
举报