Search code examples
androidimagecamera

How to auto crop after camera


I want to take a picture from camera then doing auto crop once image captured. Is there an example of source code? I feel hard to find the example


Solution

  • i suggest you to use this library Android-Image-Cropper by ArthurHub, it gives you a plenty of cropping choices (shape , size ,....) , and it also give you the choice of taking new picture or using one from the gallery

        int myColor;
        if(Build.VERSION.SDK_INT >= 21){
            myColor = ContextCompat.getColor(this, R.color.white);
        }
        else{
            myColor=getResources().getColor(R.color.white);
        }
        CropImage.activity()
                .setActivityMenuIconColor(myColor)
                .setAllowRotation(true)
                .setFixAspectRatio(true)
                .setAspectRatio(3, 2)
                .setCropShape(CropImageView.CropShape.RECTANGLE)
                .setActivityTitle("Selection d'image")
                .start(this);
    

    and you have to handle the result :

        @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    
        if(requestCode== CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE){
    
         CropImage.ActivityResult result = CropImage.getActivityResult(data);
            if (resultCode == RESULT_OK) {
                Uri resultUri = result.getUri();
                Bitmap bitmap = null;
                try {
                    bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), resultUri);
    
                    String string = resultUri.toString();
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 40, baos);
    
    
                } catch (IOException e) {
                    e.printStackTrace();
                }
    
    
            } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
                Exception error = result.getError();
            }
        }
    
    }
    

    enter image description here