PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 27, 2022

[FIXED] How to crop an image in Android

 July 27, 2022     android, crop     No comments   

Issue

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. After that my application closes because the data in this line: Bundle extras = data.getExtras(); returns null. And before that the resultCode is 0 which means it canceled. How I can fix that?


Solution

You can crop an image using an onActivityResult(). This video shows how to set it up properly with setOnClickListener().

Don't forget to set the implementation in your build.gradle:

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

Good luck! :)



Answered By - Etienne Kaiser
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing