1.从相册获取照片
private void openAlumb() {//mRxPermissions:三方权限库 mRxPermissions .request(Manifest.permission.WRITE_EXTERNAL_STORAGE) .subscribe(granted -> { if (granted) { // Always true pre-M Intent intentToPickPic = new Intent(Intent.ACTION_GET_CONTENT, null); // 如果限制上传到服务器的图片类型时可以直接写如:"image/jpeg 、 image/png等的类型" 所有类型则写 "image/*" intentToPickPic.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*"); /*是否有能处理的外部activity*/ if (intentToPickPic.resolveActivity(getPackageManager()) != null) { startActivityForResult(intentToPickPic, REQUEST_ALUBM); } } else { } }); }
2.拍照
private void takePhoto() { mRxPermissions.requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(permisssion -> { if (permisssion.granted) { if (getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY)) { //手机是否有探头 Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); /*是否有能处理的外部activity*/ if (intent.resolveActivity(getPackageManager()) != null) { try { File photoFile = creatImageFile(); Uri photoUri = FileProvider.getUriForFile(UserInfoActivity.this, "com.ore.jalon.trace.fileprovider", photoFile); intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri); } catch (IOException e) { e.printStackTrace(); } startActivityForResult(intent, REQUEST_TAKE_PHOTO); } } } else if (permisssion.shouldShowRequestPermissionRationale) { //拒绝了并且勾选了不再提示 } else { } }); }
private File creatImageFile() throws IOException { /*判断是否有外存*/ if (Environment.getExternalStorageState().equals(MEDIA_UNMOUNTED)) { return null; } String timeStamp = new SimpleDateFormat("yyyy_MMddmmss").format(new Date()); String imgFileName = "JPEG_" + timeStamp + "_"; /*保存到相册 */ File fileDirct = Environment.getExternalStoragePublicDirectory(DIRECTORY_DCIM); File imgFile = File.createTempFile(imgFileName, ".jpg", fileDirct); mCurrentPhotoPath = imgFile.getAbsolutePath(); return imgFile; }
2.fileprovider: Android7.0开始 file://Uri
不给用,那么换个 Uri 为 content://
来替代。
FileProvider使用
现在xml文件中申明
新建XML文件夹新建path.xml
最后在处理获取到的照片uri
protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {//通过三方的缩放裁切一下图片 startPhotoZoom(Uri.fromFile(new File(mCurrentPhotoPath))); } if (requestCode == REQUEST_ALUBM && resultCode == RESULT_OK) { Uri uri = data.getData(); startPhotoZoom(uri); } if (requestCode == UCrop.REQUEST_CROP && resultCode == RESULT_OK) {//获取裁切后的图片 final Uri resultUri = UCrop.getOutput(data); } } public void startPhotoZoom(Uri uri) { LogUtil.d(this.toString(), "begin cut"); try { File file = creatImageFile(); UCrop.Options options = new UCrop.Options(); options.setHideBottomControls(true); UCrop.of(uri, Uri.fromFile(file)) .withAspectRatio(1, 1) .withMaxResultSize(200, 200).withOptions(options) .start(this); } catch (IOException e) { e.printStackTrace(); } }