
从图库和相机中选择裁剪图像在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;@OverrIDeprotected 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;}@OverrIDepublic 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 belowintent.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 thisintent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);startActivityForResult(intent, 1); 总结 以上是内存溢出为你收集整理的如何从Android 7.0中的相机或图库中选择裁剪图像?全部内容,希望文章能够帮你解决如何从Android 7.0中的相机或图库中选择裁剪图像?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)