2

I am using this Crop library by SoundCloud. Selecting one imageview, slecting image, cropping and showing the result in the imageview works fine. But now I am trying to do it with two different imageviews with different specifications. I am not getting any errors nor am I seeing any results. Here's what I have tried:

//My click listeners
regCoverPhoto.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Crop.pickImage(getActivity(), EditProfileDialog.this, REQUEST_CODE_COVER);
    }
});
regUserProfile.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Crop.pickImage(getActivity(), EditProfileDialog.this, REQUEST_CODE_PROFILE);
    }
});
//Handling the result
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_CODE_PROFILE && resultCode == Activity.RESULT_OK) {
        beginCropProfile(data.getData());
    }else if(requestCode == REQUEST_CODE_COVER && resultCode == Activity.RESULT_OK){
        beginCropCover(data.getData());
    } else if (requestCode == Crop.REQUEST_CROP) {
        handleCrop(requestCode, resultCode, data);
    }
}

private void beginCropProfile(Uri source) {
    Uri destination = Uri.fromFile(new File(getActivity().getCacheDir(), "cropped"));
    Crop.of(source, destination).withAspect(ASPECT_X, ASPECT_Y).start(getActivity(), EditProfileDialog.this, REQUEST_CODE_COVER);
}

private void beginCropCover(Uri source) {
    Uri destination = Uri.fromFile(new File(getActivity().getCacheDir(), "cropped"));
    Crop.of(source, destination).asSquare().start(getActivity(), EditProfileDialog.this, REQUEST_CODE_PROFILE);
}

private void handleCrop(int requestCode, int resultCode, Intent result) {
    if (requestCode == REQUEST_CODE_COVER && resultCode == Activity.RESULT_OK) {
        regCoverPhoto.setImageURI(Crop.getOutput(result));

        mCoverPhotoUri = Crop.getOutput(result);
        uploadCoverToStorage();

        Log.d(TAG,"ResultCover: " + Crop.getOutput(result).toString());
    }else if(requestCode == REQUEST_CODE_PROFILE && resultCode == Activity.RESULT_OK){
        regUserProfile.setImageURI(Crop.getOutput(result));
        mProfilePhotoUri = Crop.getOutput(result);
        uploadProfileToStorage();
        Log.d(TAG,"ResultProfile: " + Crop.getOutput(result).toString());
    } else if (resultCode == Crop.RESULT_ERROR) {
        Snackbar.make(getView(), Crop.getError(result).getMessage(), Snackbar.LENGTH_LONG).show();
    }
}
Steve C.
  • 1,333
  • 3
  • 19
  • 50

4 Answers4

1

I haven't used this library particularly, but custom request codes seem to be the problem.

Use different request codes for picking and cropping (total of 4 request codes) as you will need to handle them differently, and update onActivityResult(), handleCrop() to reflect that.

See https://gist.github.com/vibinr/fcf54c5e7ab63b9184432cc44c9a1494

Vibin
  • 843
  • 6
  • 18
  • I considered that, but the class "Crop" from the crop library calls the REQUEST_CROP requestCode by default for the returned cropped image. What I don't know is how to separate the two if they need to be different. – Steve C. Aug 18 '17 at 02:15
  • The library states you can pass a custom requestCode for the initial "select image" request but what about getting the returned image for two different crops from within the same activity? Do you think I could modify the Crop class to call two different crop request codes? – Steve C. Aug 18 '17 at 02:17
  • I can see that Crop has many variations of its #start() method, one which takes in Context, Fragment and custom request code. I think that's what you need. – Vibin Aug 18 '17 at 04:16
  • Yes. That is the method I am calling in the onClickListeners for each ImageView with different request codes. onActivityResult gets back the REQUEST_CROP code after crop though which doesn't show any results in the imageviews like I would expect. – Steve C. Aug 18 '17 at 05:10
  • In the OnClickListeners you are calling Crop#pickImage() with your custom request codes, but you should also pass the custom request codes to #start(), in #beginCropProfile() and #beginCropCover(). – Vibin Aug 18 '17 at 05:22
  • I didn't notice that. I will try that and get back to you with my results. – Steve C. Aug 18 '17 at 06:13
  • You'll probably also have to use different request codes for selecting them (cover, profile) and cropping them, as the handling is done in a single onActivityResult() and you'll need to differentiate selecting from cropping. – Vibin Aug 18 '17 at 06:20
  • I added the custom request codes to the #start() method within beginCrop... but still don't get a result. Not even the log lines defined show in the logcat. Original image still remains in the imageview – Steve C. Aug 18 '17 at 06:38
  • I updated my post with the added custom request codes for each beginCrop... method. I also ran with breakpoints and it doesn't look like the method handleCrop in my class is being called. I'm confused. – Steve C. Aug 18 '17 at 06:53
  • What if I declared custom "crop" request codes within #handleCrop()? And replaced the line `else if (requestCode == Crop.RESULT_CROP)` with just "else"? – Steve C. Aug 18 '17 at 06:58
  • Can you try this gist? https://gist.github.com/vibinr/fcf54c5e7ab63b9184432cc44c9a1494 I tried with different request codes for picking and cropping. – Vibin Aug 18 '17 at 07:05
  • smh Still nothing. :/ Debugging the process shows the resultCode returning as -1 after cropping and intent data being empty. – Steve C. Aug 18 '17 at 07:14
  • Ok it works now. I was missing the custom crop request codes in the "if" statement for #handleCrop(). If you could, please add that to your answer for others that may run into the problem as well. And thank you so much!! The only issue I have now is that the profile crops with the declared aspect ratio and the cover crops as a square. Which is backwards but I think if I swap the code it should fix the problem. – Steve C. Aug 18 '17 at 07:23
1
  1. List item

Here is a complete code of the images selection to crop and uploading to server using rest client with retrofit library Here few variables are used extra as for my use please ignore them

Also i'm using these library inside gradel

 compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.theartofdev.edmodo:android-image-cropper:2.4.+'
compile 'com.squareup.retrofit:retrofit:1.6.1'

And inside Mainfrest i have specifed this as <activity android:name="com.theartofdev.edmodo.cropper.CropImageActivity" android:screenOrientation="portrait" />

side2Image.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
    image_name = "image_side_2";
    image_number_5 = "image_side_2";
    imagePath = Environment.getExternalStorageDirectory().toString();
    new File(imagePath).mkdir();

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
    String name = dateFormat.format(new Date());
    savedFileDestination = new File(imagePath, name + ".jpg");

    CropImage.activity(Uri.fromFile(savedFileDestination));
    CropImage.startPickImageActivity(TradeAddProduct.this);
}

backImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
    image_name = "image_back";
    image_number_6 = "image_back";
    imagePath = Environment.getExternalStorageDirectory().toString();
    new File(imagePath).mkdir();

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
    String name = dateFormat.format(new Date());
    savedFileDestination = new File(imagePath, name + ".jpg");

    CropImage.activity(Uri.fromFile(savedFileDestination));
    CropImage.startPickImageActivity(TradeAddProduct.this);
}

@Override
@SuppressLint("NewApi")
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CropImage.PICK_IMAGE_CHOOSER_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
        imageUri = CropImage.getPickImageResultUri(this, data);

        // For API >= 23 we need to check specifically that we have permissions to read external storage.
        if (CropImage.isReadExternalStoragePermissionsRequired(this, imageUri)) {
            // request permissions and handle the result in onRequestPermissionsResult()
            mCropImageUri = imageUri;
            requestPermissions(new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
        } else {
            // no permissions required or already grunted, can start crop image activity
            startCropImageActivity(imageUri);
        }
    }

    // handle result of CropImageActivity
    if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
        CropImage.ActivityResult result = CropImage.getActivityResult(data);
        if (resultCode == RESULT_OK) {

            if (image_name.equals("image_front")) {
                image.setImageURI(result.getUri());
            } else if (image_name.equals("image_top")) {
                topImage.setImageURI(result.getUri());
            } else if (image_name.equals("image_bottom")) {
                bottomImage.setImageURI(result.getUri());
            } else if (image_name.equals("image_side_1")) {
                side1Image.setImageURI(result.getUri());
            } else if (image_name.equals("image_side_2")) {
                side2Image.setImageURI(result.getUri());
            } else if (image_name.equals("image_back")) {
                backImage.setImageURI(result.getUri());
            }

            cropped = result.getUri();
            File path = getExternalCacheDir();
            new File(String.valueOf(path)).mkdir();

            imagePath = Environment.getExternalStorageDirectory().toString();
            new File(imagePath).mkdir();

            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddhhmmss");
            String name22 = dateFormat.format(new Date());

// String helloWorld = cropped.toString(); // String hhhh=helloWorld.substring(helloWorld.indexOf(":")+1,helloWorld.indexOf("/")); // String name="snehal_go"; savedFileDestination = new File(imagePath, name22 + ".jpg");

            ContextWrapper cw = new ContextWrapper(getApplicationContext());
            // path to /data/data/yourapp/app_data/imageDir
            File directory = cw.getDir("Webmirchi..", Context.MODE_PRIVATE);

            String ALLOWED_CHARACTERS = "QWERTYUIOPASDFGHJKLZXCVBNM0123456789qwertyuiopasdfghjklzxcvbnm";
            Random generator = new Random();
            randomStringBuilder = new StringBuilder();
            int randomLength = 10;
            for (int i = 0; i < randomLength; i++) {
                randomStringBuilder.append(ALLOWED_CHARACTERS.charAt(generator.nextInt(ALLOWED_CHARACTERS.length())));
            }


            // Create imageDir
            mypath = new File(directory, sessionMail + "-" + ProductId + ".jpg");

            FileOutputStream fos = null;
            try {
                Bitmap bitmapImage = MediaStore.Images.Media.getBitmap(this.getContentResolver(), cropped);

                fos = new FileOutputStream(mypath);
                // Use the compress method on the BitMap object to write image to the OutputStream
                bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
                Log.i("File", mypath.toString());


                if (image_name.equals("image_front")) {
                    uploadImage_front();
                } else if (image_name.equals("image_top")) {
                    uploadImage_top();
                } else if (image_name.equals("image_bottom")) {
                    uploadImage_bottom();
                } else if (image_name.equals("image_side_1")) {
                    uploadImage_side1();
                } else if (image_name.equals("image_side_2")) {
                    uploadImage_side2();
                } else if (image_name.equals("image_back")) {
                    uploadImage_back();
                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }


        } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
            // Toast.makeText(this, "Cropping failed: " + result.getError(), Toast.LENGTH_LONG).show();
        }
    }
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    if (mCropImageUri != null && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        // required permissions granted, start crop image activity
        startCropImageActivity(mCropImageUri);
    } else {
        Toast.makeText(this, "Cancelling, required permissions are not granted", Toast.LENGTH_LONG).show();
    }
}
   */
private void startCropImageActivity(Uri imageUri) {
    CropImage.activity(imageUri)
            .setGuidelines(CropImageView.Guidelines.ON)
            .setMultiTouchEnabled(false)
            .setMinCropWindowSize(600, 600)
            .setAspectRatio(2, 2)
            .setRequestedSize(500, 500)
            .start(this);
}
Snehal Gongle
  • 337
  • 3
  • 16
0

Please refer the following url.This may help you. "https://www.bignerdranch.com/blog/understanding-androids-layoutinflater-inflate/"

Shanmugapriya
  • 57
  • 3
  • 15
0

I'm not good in english...

// took extra int
    static int a=0;

    private void onClickData() {
        cover_imgBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
// change the value
                a=1;
                CropImage.activity()
                        .setAspectRatio(10,15)
                        .start(AddNewBooks_Images.this);
            }
        });

        author_imgBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
// change the value 
                a=2;
                CropImage.activity()
                        .setAspectRatio(10,15)
                        .start(AddNewBooks_Images.this);
            }
        });

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//here used the value
        if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK && data!=null && a==1){
// change the value again
            a=0;
        }
//here used the value
        if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK && data!=null && a==2){
// change the value again
            a=0;
        }
    }
DuDa
  • 3,718
  • 4
  • 16
  • 36