如何从Android 7.0中的相机或图库中选择裁剪图像?
作者:互联网
从图库和相机中选择裁剪图像在Android 7.0以下完成,但在Android Naught中它在相机中崩溃.我使用fileprovider但不起作用.
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button mBtn;
private Context context;
private static final int SELECT_PICTURE_CAMARA = 101, SELECT_PICTURE = 201, CROP_IMAGE = 301;
private Uri outputFileUri;
String mCurrentPhotoPath;
private Uri selectedImageUri;
private File finalFile = null;
private ImageView imageView;
private PermissionUtil permissionUtil;
Uri fileUri;
File file = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBtn = (Button) findViewById(R.id.btn_img);
imageView = (ImageView) findViewById(R.id.img_photo);
permissionUtil = new PermissionUtil();
mBtn.setOnClickListener(this);
context = this;
}
@Override
public void onClick(View view) {
selectImageOption();
}
private void selectImageOption() {
final CharSequence[] items = {"Capture Photo", "Choose from Gallery", "Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Capture Photo")) {
if (permissionUtil.checkMarshMellowPermission()) {
if (permissionUtil.verifyPermissions(MainActivity.this, permissionUtil.getCameraPermissions()))
onClickCamera();
else
ActivityCompat.requestPermissions(MainActivity.this, permissionUtil.getCameraPermissions(), SELECT_PICTURE_CAMARA);
} else
onClickCamera();
} else if (items[item].equals("Choose from Gallery")) {
if (permissionUtil.checkMarshMellowPermission()) {
if (permissionUtil.verifyPermissions(MainActivity.this, permissionUtil.getGalleryPermissions()))
onClickGallery();
else
ActivityCompat.requestPermissions(MainActivity.this, permissionUtil.getGalleryPermissions(), SELECT_PICTURE);
} else
onClickGallery();
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
selectedImageUri = data.getData();
cropImage(selectedImageUri);
} else if (requestCode == CROP_IMAGE) {
Uri imageUri = Uri.parse(mCurrentPhotoPath);
File file = new File(imageUri.getPath());
try {
InputStream ims = new FileInputStream(file);
imageView.setImageBitmap(BitmapFactory.decodeStream(ims));
} catch (FileNotFoundException e) {
return;
}
} else if (requestCode == SELECT_PICTURE_CAMARA && resultCode == Activity.RESULT_OK) {
cropImage1();
}
}
}
private void onClickCamera() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(context.getPackageManager()) != null) {
/* File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
}
if (photoFile != null) {
Uri photoURI;
if (Build.VERSION.SDK_INT >= 24) {
photoURI = FileProvider.getUriForFile(MainActivity.this,
BuildConfig.APPLICATION_ID + ".fileprovider", photoFile);
} else {
photoURI = Uri.fromFile(photoFile);
}
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, SELECT_PICTURE_CAMARA);
}*/
ContentValues values = new ContentValues(1);
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpg");
fileUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
startActivityForResult(takePictureIntent, SELECT_PICTURE_CAMARA);
} else {
Toast.makeText(this, getString(R.string.error_no_camera), Toast.LENGTH_LONG).show();
}
}
private void onClickGallery() {
List<Intent> targets = new ArrayList<>();
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK);
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
List<ResolveInfo> candidates = getApplicationContext().getPackageManager().queryIntentActivities(intent, 0);
for (ResolveInfo candidate : candidates) {
String packageName = candidate.activityInfo.packageName;
if (!packageName.equals("com.google.android.apps.photos") && !packageName.equals("com.google.android.apps.plus") && !packageName.equals("com.android.documentsui")) {
Intent iWantThis = new Intent();
iWantThis.setType("image/*");
iWantThis.setAction(Intent.ACTION_PICK);
iWantThis.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
iWantThis.setPackage(packageName);
targets.add(iWantThis);
}
}
if (targets.size() > 0) {
Intent chooser = Intent.createChooser(targets.remove(0), "Select Picture");
chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, targets.toArray(new Parcelable[targets.size()]));
startActivityForResult(chooser, SELECT_PICTURE);
} else {
Intent intent1 = new Intent(Intent.ACTION_PICK);
intent1.setType("image/*");
startActivityForResult(Intent.createChooser(intent1, "Select Picture"), SELECT_PICTURE);
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
if (Build.VERSION.SDK_INT >= 24) {
mCurrentPhotoPath = String.valueOf(FileProvider.getUriForFile(MainActivity.this,
BuildConfig.APPLICATION_ID + ".provider", image));
} else {
mCurrentPhotoPath = String.valueOf(Uri.fromFile(image));
}
return image;
}
/*private Uri createImageUri(){
ContentResolver contentResolver=getContentResolver();
ContentValues cv=new ContentValues();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
cv.put(MediaStore.Images.Media.TITLE,timeStamp);
return contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,cv);
}*/
private void cropImage(Uri selectedImageUri) {
Intent cropIntent = new Intent("com.android.camera.action.CROP");
cropIntent.setDataAndType(selectedImageUri, "image/*");
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1.5);
cropIntent.putExtra("return-data", true);
outputFileUri = Uri.fromFile(createCropFile());
cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cropIntent, CROP_IMAGE);
}
private void cropImage1() {
Intent cropIntent = new Intent("com.android.camera.action.CROP");
cropIntent.setDataAndType(fileUri, "image/*");
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1.5);
cropIntent.putExtra("return-data", true);
if (Build.VERSION.SDK_INT >= 24) {
outputFileUri = FileProvider.getUriForFile(MainActivity.this,
BuildConfig.APPLICATION_ID + ".provider", createCropFile());
} else
outputFileUri = Uri.fromFile(createCropFile());
cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cropIntent, CROP_IMAGE);
/* ContentValues values = new ContentValues(1);
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpg");
outputFileUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
cropIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cropIntent, CROP_IMAGE);*/
}
private File createCropFile() {
File storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
// path = path + (timeStamp + "1jpg");
try {
file = File.createTempFile(timeStamp, ".jpg", storageDir);
} catch (IOException e) {
e.printStackTrace();
}
/*if (Build.VERSION.SDK_INT >= 24)
mCurrentPhotoPath = String.valueOf(FileProvider.getUriForFile(MainActivity.this,
BuildConfig.APPLICATION_ID + ".provider", file));
else*/
mCurrentPhotoPath = String.valueOf(Uri.fromFile(file));
return file;
}
}
这项工作在所有设备中但不在> = android 7.0 Naught设备中
解决方法:
我只是在Nexus6p android N上解决了这个问题,你需要授予uri权限,这样系统摄像头才能暂时访问文件等待裁剪,因为StrictMode Android N不支持传递文件:Uri在一个Intent extra中再看看Scheme Ban in N Developer Preview,我们使用FileProvider代替.这是我的源代码:
AndroidManifest.xml中
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="dreamgo.corp.provider"
android:grantUriPermissions="true"
android:exported="false">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/filepaths"/>
</provider>
filepaths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="images" path="."/>
</paths>
MainActivity.java
Uri photoURI = FileProvider.getUriForFile(context, "dreamgo.corp.provider", file);
//grant uri with essential permission the first arg is the The packagename you would like to allow to access the Uri.
context.grantUriPermission("com.android.camera",photoURI,
Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(photoURI, "image/*");
//you must setup two line below
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 200);
intent.putExtra("return-data", true);
//you must setup this
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(intent, 1);
标签:android-7-0-nougat,android-gallery,android 来源: https://codeday.me/bug/20190926/1821505.html