1. Picture selection
Intent intent = new Intent(Intent.ACTION_PICK); intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*"); startActivityForResult(intent, AVATAR_PICTURE);
2. Select image callback
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case AVATAR_PICTURE://Callback selected from gallery //filePath = data.getData().getPath(); if (data != null) {//Not empty, indicating that it is the avatar selected by the gallery Are you = data.getData (); if (uri == null) return; Cursor c = getContentResolver().query(uri, new String[]{MediaStore.Images.Media.DATA}, null, null, null); if (c == null) return; boolean moveToNext = c.moveToNext(); if (moveToNext) { mFilePath = c.getString(0); } c.close(); //Cancel the operation, and no picture is selected } else { return; } cropRawPhoto (Uri.fromFile (new File (mFilePath)), mIvAvatar, AVATAR_CROP); break; case AVATAR_CAMERA://Callback after taking a photo if (resultCode == RESULT_OK) { mFilePath = mCameraPath; cropRawPhoto (Uri.fromFile (new File (mFilePath)), mIvAvatar, AVATAR_CROP); //update gallery Uri localUri = Uri.fromFile (new File (mFilePath)); Intent localIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, localUri); sendBroadcast (localIntent); //Cancel return, } else if (requestCode == RESULT_CANCELED) { } break;
case AVATAR_CROP://Callback after cropping if (data != null) { Bundle extras = intent.getExtras(); if (extras != null) Bitmap photo = extras.getParcelable("data"); } else { return; } break;
3. Call to take pictures
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // Determine if the memory card is available and store the photo file if (StorageUtils.hasSdcard()) { File file = new File(Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES), System.currentTimeMillis() + ".jpg"); mCameraPath = file.getAbsolutePath(); Uri uri = Uri.fromFile (file); intent.putExtra(MediaStore.EXTRA_OUTPUT, uri); } startActivityForResult(intent, AVATAR_CAMERA);
4. Call the crop function after taking a photo
** * Crop the original picture */ public void cropRawPhoto(Uri uri, CircleImageView ivAvatar, int CODE_RESULT_REQUEST) { Intent intent = new Intent("com.android.camera.action.CROP"); intent.setDataAndType(uri, "image/*"); // set crop intent.putExtra("crop", "true"); // aspectX , aspectY : aspect ratio intent.putExtra("aspectX", 1); intent.putExtra("aspectY", 1); // outputX , outputY : crop image width and height intent.putExtra("outputX", ivAvatar.getWidth()); intent.putExtra("outputY", ivAvatar.getHeight()); intent.putExtra("return-data", true); startActivityForResult(intent, CODE_RESULT_REQUEST); }