Skip to content

Instantly share code, notes, and snippets.

@Muraveiko
Created October 27, 2024 09:57
Show Gist options
  • Save Muraveiko/aa38f6a2670871b6e2aba00eb6d152b9 to your computer and use it in GitHub Desktop.
Save Muraveiko/aa38f6a2670871b6e2aba00eb6d152b9 to your computer and use it in GitHub Desktop.
Conract for Crop
public class PictureCropContract extends ActivityResultContract<PictureCropContract.CropParam,Bitmap> {
static public class CropParam {
public Uri uri;
// does not work for the sizes I need together with the key return-data = true
public int width = 2480;
public int height = 3507;
}
@NonNull
@Override
public Intent createIntent(@NonNull Context context, CropParam param) {
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(param.uri, "image/jpeg");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.putExtra("crop", "true");
intent.putExtra("aspectX", param.width);
intent.putExtra("aspectY", param.height);
intent.putExtra("outputX", param.width);
intent.putExtra("outputY", param.height);
intent.putExtra("return-data", true); // may overflow extras size
intent.putExtra("outputFormat",
Bitmap.CompressFormat.JPEG.toString());
intent.putExtra("noFaceDetection", true);
return intent;
}
@Override
public Bitmap parseResult(int code, @Nullable Intent data) {
// For larger sizes, you can use the contents Uri,
// but then copies of the image remain in the gallery
if(code == RESULT_OK){
Bundle extras;
if (data != null) {
extras = data.getExtras();
if (extras != null) {
return extras.getParcelable("data");
}
}
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment