【问题标题】:How to crop two different images in the same activity with different parameters in Android?如何在Android中使用不同参数裁剪同一活动中的两个不同图像?
【发布时间】:2018-01-14 06:04:46
【问题描述】:

我正在使用 SoundCloud 的 Crop 库。选择一个图像视图,选择图像,裁剪并在图像视图中显示结果工作正常。但现在我正在尝试使用两种不同规格的不同图像视图来做到这一点。我没有收到任何错误,也没有看到任何结果。这是我尝试过的:

//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();
    }
}

【问题讨论】:

  • 我只是想知道您是要一次裁剪两张图像还是一个接一个地裁剪????使用不同的 onclick 侦听器?? @史蒂夫C
  • @SnehalGongle 一个接一个

标签: java android imageview crop


【解决方案1】:

请参考以下网址。这可能对您有所帮助。 "https://www.bignerdranch.com/blog/understanding-androids-layoutinflater-inflate/"

【讨论】:

    【解决方案2】:

    我没有特别使用过这个库,但是自定义请求代码似乎是个问题。

    使用不同的请求代码进行挑选和裁剪(总共 4 个请求代码),因为您需要以不同的方式处理它们,并更新 onActivityResult()handleCrop() 以反映这一点。

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

    【讨论】:

    • 我考虑过这一点,但裁剪库中的“裁剪”类默认为返回的裁剪图像调用 REQUEST_CROP 请求代码。我不知道如果它们需要不同,如何将两者分开。
    • 库声明您可以为初始“选择图像”请求传递自定义 requestCode,但是从同一活动中获取两种不同作物的返回图像呢?你认为我可以修改 Crop 类来调用两个不同的裁剪请求代码吗?
    • 我可以看到 Crop 的#start() 方法有很多变体,其中一种包含上下文、片段和自定义请求代码。我认为这就是您所需要的。
    • 是的。这就是我在 onClickListeners 中为每个具有不同请求代码的 ImageView 调用的方法。 onActivityResult 在裁剪后取回 REQUEST_CROP 代码,但它并没有像我预期的那样在图像视图中显示任何结果。
    • 在 OnClickListeners 中,您使用自定义请求代码调用 Crop#pickImage(),但您还应该在 #beginCropProfile() 和 #beginCropCover() 中将自定义请求代码传递给 #start() .
    【解决方案3】:
    1. 列表项

    这是一个完整的图像选择代码,使用带有改造库的rest客户端裁剪和上传到服务器这里很少使用变量,因为我的使用请忽略它们

    我也在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'
    

    在 Mainfrest 中,我将其指定为 <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("/")); // 字符串名称="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);
    }
    

    【讨论】:

      【解决方案4】:

      我的英文不好……

      // 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;
              }
          }
      

      【讨论】:

        猜你喜欢
        • 2020-10-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多