简体   繁体   English

如何在 Android 中裁剪图像

[英]How to crop an image in Android

I want choose a image from the gallery and crop that.我想从图库中选择一张图片并裁剪它。 I can choose the picture but I can't crop that yet.我可以选择图片,但我还不能裁剪。 That is my code I have yet:那是我的代码我还没有:

public static final int PICK_IMAGE = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_upload);

    Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(intent, PICK_IMAGE);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    
    if(requestCode == PICK_IMAGE && data != null){
        Intent cropIntent = new Intent("com.android.camera.action.CROP");
        cropIntent.setData(data.getData());
        cropIntent.putExtra("crop", "true");
        cropIntent.putExtra("aspectX", 1);
        cropIntent.putExtra("aspectY", 1);
        cropIntent.putExtra("outputX", 450);
        cropIntent.putExtra("outputY", 350);
        cropIntent.putExtra("return-data", true);
        startActivityForResult(cropIntent, 1);
    }else if(requestCode == 1){
        Log.d("resultCode", String.valueOf(resultCode));
        Bundle extras = data.getExtras();
        Bitmap bitmap = extras.getParcelable("data");
        ImageView test = findViewById(R.id.test);
        test.setImageBitmap(bitmap);
        test.setScaleType(ImageView.ScaleType.FIT_XY);
    }
    super.onActivityResult(requestCode, resultCode, data);
}

When I start the app I can select a picture.当我启动应用程序时,我可以 select 一张图片。 After that my application closes because the data in this line: Bundle extras = data.getExtras();之后我的应用程序关闭,因为此行中的数据Bundle extras = data.getExtras(); returns null.返回 null。 And before that the resultCode is 0 which means it canceled.在此之前, resultCode为 0,这意味着它已取消。 How I can fix that?我该如何解决?

You can crop an image using an onActivityResult() .您可以使用onActivityResult()裁剪图像。 This video shows how to set it up properly with setOnClickListener() .视频展示了如何使用setOnClickListener()正确设置它。

Don't forget to set the implementation in your build.gradle :不要忘记在您的build.gradle中设置implementation

implementation 'com.theartofdev.edmodo:android-image-cropper:2.4.+'

Good luck: :)祝你好运: :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM