Cropping Image in Android (Crop Intent)

ⅰ亾dé卋堺 提交于 2019-11-30 05:50:43

You can try this.

private void doCrop(Uri picUri) {
    try {

        Intent cropIntent = new Intent("com.android.camera.action.CROP");

        cropIntent.setDataAndType(picUri, "image/*");           
        cropIntent.putExtra("crop", "true");           
        cropIntent.putExtra("aspectX", 1);
        cropIntent.putExtra("aspectY", 1);           
        cropIntent.putExtra("outputX", 128);
        cropIntent.putExtra("outputY", 128);           
        cropIntent.putExtra("return-data", true);
        startActivityForResult(cropIntent, CROP_PIC_REQUEST_CODE);
    }
    // respond to users whose devices do not support the crop action
    catch (ActivityNotFoundException anfe) {
        // display an error message
        String errorMessage = "Whoops - your device doesn't support the crop action!";
        Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
        toast.show();
    }
}

Get Uri from bitmap

public Uri getImageUri(Context inContext, Bitmap inImage) {
  ByteArrayOutputStream bytes = new ByteArrayOutputStream();
  inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
  String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
  return Uri.parse(path);
}

Declare

final int CROP_PIC_REQUEST_CODE = 1;

Than simply

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == CROP_PIC_REQUEST_CODE) {
        if (data != null) {
            Bundle extras = data.getExtras();
            Bitmap bitmap= extras.getParcelable("data");
            yourImageView.setImageBitmap(bitmap);
        }
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!