Android 图像裁剪在片段中不工作

Android 图像裁剪在片段中不工作,android,camera,fragment,Android,Camera,Fragment,下面是我的代码,当我使用“活动”时,它正在工作,但当我在片段中执行此代码时,然后在从“多媒体资料”中选择“图像”或从相机中选择“捕获”后,它将不显示裁剪选项。另外,我的图像未显示在imageView中 下面是我的相机处理器: public class CameraHandler { public static int IMAGE_PIC_CODE = 1000, CROP_CAMERA_REQUEST = 1001, CROP_GALLARY_REQUEST =

下面是我的代码,当我使用“活动”时,它正在工作,但当我在片段中执行此代码时,然后在从“多媒体资料”中选择“图像”或从相机中选择“捕获”后,它将不显示裁剪选项。另外,我的图像未显示在imageView中

下面是我的相机处理器:

public class CameraHandler {
    public static int IMAGE_PIC_CODE = 1000, CROP_CAMERA_REQUEST = 1001,
            CROP_GALLARY_REQUEST = 1002;
    private Intent imageCaptureintent;
    private boolean isActivityAvailable;
    Context context;
    private List<ResolveInfo> cameraList;
    List<Intent> cameraIntents;
    Uri outputFileUri;
    Intent galleryIntent;
    Uri selectedImageUri;
    private String cameraImageFilePath, absoluteCameraImagePath;
    Bitmap bitmap;
    ImageView ivPicture;

    String ivPicture1 = String.valueOf(ivPicture);

    public CameraHandler(Context context) {
        this.context = context;
        setFileUriForCameraImage();
    }

    public void setIvPicture(ImageView ivPicture) {
        this.ivPicture = ivPicture;
    }

    private void setFileUriForCameraImage() {
        File root = new File(Environment.getExternalStorageDirectory()
                + File.separator + "MyDir" + File.separator);
        root.mkdirs();
        final String fname = "image.jpg";
        final File sdImageMainDirectory = new File(root, fname);
        absoluteCameraImagePath = sdImageMainDirectory.getAbsolutePath();
        outputFileUri = Uri.fromFile(sdImageMainDirectory);
    }

    public String getCameraImagePath() {
        return cameraImageFilePath;
    }

    private void getActivities() {
        imageCaptureintent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        PackageManager packageManager = ((Activity) context)
                .getPackageManager();
        this.cameraList = packageManager.queryIntentActivities(
                imageCaptureintent, 0);
        if (cameraList.size() > 0) {
            isActivityAvailable = true;
        } else {
            isActivityAvailable = false;
        }
    }

    private void fillCameraActivities() {
        getActivities();
        if (!isActivityAvailable) {
            return;
        }
        cameraIntents = new ArrayList<Intent>();
        for (ResolveInfo resolveInfo : cameraList) {
            Intent intent = new Intent(imageCaptureintent);
            intent.setPackage(resolveInfo.activityInfo.packageName);
            intent.setComponent(new ComponentName(
                    resolveInfo.activityInfo.packageName,
                    resolveInfo.activityInfo.name));
            intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
            cameraIntents.add(intent);
        }
    }

    private void fillGallaryIntent() {
        galleryIntent = new Intent();
        galleryIntent.setType("image/*");
        galleryIntent.setAction(Intent.ACTION_PICK);
    }

    public void showView() {
        fillCameraActivities();
        fillGallaryIntent();
        // Chooser of filesystem options.
        final Intent chooserIntent = Intent.createChooser(galleryIntent,
                "Select Source");

        // Add the camera options.
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
                cameraIntents.toArray(new Parcelable[] {}));

        ((Activity) context).startActivityForResult(chooserIntent,
                IMAGE_PIC_CODE);
    }

    private Bitmap getBitmapFromURL(String src) {

        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(src, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, 192, 256);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(src, options);

    }

    private int calculateInSampleSize(BitmapFactory.Options options,
                                      int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {

            final int halfHeight = height / 2;
            final int halfWidth = width / 2;

            // Calculate the largest inSampleSize value that is a power of 2
            // and keeps both
            // height and width larger than the requested height and width.
            while ((halfHeight / inSampleSize) > reqHeight
                    && (halfWidth / inSampleSize) > reqWidth) {
                inSampleSize *= 2;
            }
        }

        return inSampleSize;
    }

    public String getRealPathFromURI(Context context, Uri contentUri) {
        Cursor cursor = null;
        try {
            String[] proj = { MediaStore.Images.Media.DATA };
            cursor = context.getContentResolver().query(contentUri, proj, null,
                    null, null);
            int column_index = cursor
                    .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }

    public void onResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == IMAGE_PIC_CODE) {
                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                    Log.v("", "ics");
                } else {
                    Log.v("", " not ics");
                }
                boolean isCamera;
                if (data == null) {
                    isCamera = true;
                } else {
                    final String action = data.getAction();

                    if (action == null) {
                        isCamera = false;
                    } else {
                        isCamera = action
                                .equals(MediaStore.ACTION_IMAGE_CAPTURE);
                    }
                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH
                            && action != null) {
                        Log.v("", "action = null");
                        isCamera = true;
                    } else {
                        Log.v("", "action is not null");
                    }
                }
                if (isCamera) {
                    selectedImageUri = outputFileUri;
                    onResultCameraOK();
                } else {
                    selectedImageUri = data == null ? null : data.getData();
                    onResultGalleryOK();
                }
            }
        }

        if (requestCode == CROP_CAMERA_REQUEST) {
            if (resultCode == Activity.RESULT_OK) {
                resultOnCropOkOfCamera(data);
            } else if (resultCode == Activity.RESULT_CANCELED) {
                resultOnCroppingCancel();
            }
        }

        if (requestCode == CROP_GALLARY_REQUEST) {
            if (resultCode == Activity.RESULT_OK) {
                resultOnCropOkOfGallary(data);
            } else if (resultCode == Activity.RESULT_CANCELED) {
                resultOnCroppingCancel();
            }
        }

    }

    private void doCropping(int code) {
        Log.v("", this.cameraImageFilePath);
        Intent cropIntent = new Intent("com.android.camera.action.CROP");
        cropIntent.setDataAndType(selectedImageUri, "image/*");
        cropIntent.putExtra("crop", "true");
        cropIntent.putExtra("aspectX", 1);
        cropIntent.putExtra("aspectY", 1);
        cropIntent.putExtra("outputX", 256);
        cropIntent.putExtra("outputY", 256);
        cropIntent.putExtra("return-data", true);
        try {
            ((Activity) context).startActivityForResult(cropIntent, code);
        } catch (Exception e) {

        }
    }

    private void onResultCameraOK() {
        this.cameraImageFilePath = absoluteCameraImagePath;
        this.bitmap = getBitmapFromURL(cameraImageFilePath);
        doCropping(CROP_CAMERA_REQUEST);
    }

    private void onResultGalleryOK() {
        this.cameraImageFilePath = selectedImageUri.toString();
        this.bitmap = getBitmapFromURL(getRealPathFromURI(context,
                selectedImageUri));
        doCropping(CROP_GALLARY_REQUEST);
    }

    private void resultOnCropOkOfCamera(Intent data) {
        this.bitmap = data.getExtras().getParcelable("data");
        Log.v("", "cameraImageFilePath on crop camera ok => "
                + cameraImageFilePath);
        setImageProfile();
    }

    private void resultOnCropOkOfGallary(Intent data) {
        Bundle extras2 = data.getExtras();
        this.bitmap = extras2.getParcelable("data");
        setImageProfile();
    }

    private void resultOnCroppingCancel() {
        Log.v("", "do cropping cancel" + cameraImageFilePath);
        setImageProfile();
    }

    private void setImageProfile() {
        Log.v("", "cameraImagePath = > " + cameraImageFilePath);
        if (ivPicture != null) {
            if (bitmap != null) {
                ivPicture.setImageBitmap(bitmap);

                String ivPicture =ConDetTenthFragment.getStringImage(bitmap);

                Log.d("byte code -", ivPicture);

                /*Intent i = new Intent(context, ImageUpload.class);

                String getrec = ivPicture;

                //Create the bundle
                Bundle bundle = new Bundle();

                //Add your data to bundle
                bundle.putString("moin", getrec);

                //Add the bundle to the intent
                i.putExtras(bundle);

                //Fire that second activity
                context.startActivity(i);*/

            } else {
                Log.v("", "bitmap is null");
            }
        }
    }

    public String getVar1() {
        return ivPicture1;
    }

    /*public String getStringImage(Bitmap bmp){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] imageBytes = baos.toByteArray();
        String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
        return encodedImage;
    }*/
}


Below is my Fragment Code:


public class ConDetTenthFragment extends Fragment {

    static String FileByte;
    String FileName;
    String resultlog;

    ImageView ivProfile;
    Context context = getActivity();
    Button btnUpload, send;
    CameraHandler cameraHandler;
    private ProgressDialog pDialog;

    static String abc;

       @Override
       public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
           View rootView = inflater.inflate(R.layout.con_det_tenth_fragment, container, false);
           /*TextView tv = (TextView) v.findViewById(R.id.tvFragFirst);
           tv.setText(getArguments().getString("msg"));*/

           ivProfile = (ImageView) rootView.findViewById(R.id.iv_upload);
           btnUpload = (Button) rootView.findViewById(R.id.btn_upload_image);
           send = (Button) rootView.findViewById(R.id.btnsend);
           cameraHandler = new CameraHandler(context);
           cameraHandler.setIvPicture(ivProfile);

           // Progress dialog
           pDialog = new ProgressDialog(getActivity());
           pDialog.setCancelable(false);
           pDialog.setMessage("Please Wait");


           btnUpload.setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View v) {

                   cameraHandler.showView();

               }
           });

           send.setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View v) {
                   new async().execute();
               }
           });


       return rootView;
   }


    public static ConDetTenthFragment newInstance(String text) {

        ConDetTenthFragment f = new ConDetTenthFragment();
        Bundle b = new Bundle();
        b.putString("msg", text);

        f.setArguments(b);

        return f;
    }


    public static String getStringImage(Bitmap bmp){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        byte[] imageBytes = baos.toByteArray();
        String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);

        abc = encodedImage;

        //encodedImage = FileByte.setText().toString();

        return encodedImage;
    }

    // Async task to perform login operation
    class async extends AsyncTask<String, Void, String> {


        @Override
        protected String doInBackground(String... params) {

            //Get the bundle
            /*Bundle bundle = getIntent().getExtras();

            //Extract the data…
            String stuff = bundle.getString("moin");*/

            SoapObject request = new SoapObject(namespace, method_name);
            request.addProperty(parameter, abc);//add the parameters
            request.addProperty(parameter2, "moin.jpeg");

            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);//set soap version
            envelope.setOutputSoapObject(request);
            envelope.dotNet = true;
            try {
                HttpTransportSE androidHttpTransport = new HttpTransportSE(url);
                // this is the actual part that will call the webservice
                androidHttpTransport.call(soap_action, envelope);
                //  SoapPrimitive prim = (SoapPrimitive) envelope.getResponse();  // Get the SoapResult from the envelope body.
                SoapObject response = (SoapObject) envelope.bodyIn;
                //  resultlog=prim.toString();

                hideDialog();

            } catch (Exception e) {
                e.printStackTrace();
            }

            return resultlog;

        }
    }


    /*@Override
    public void onClick(View view) {
        if (view == btnUpload) {
            cameraHandler.showView();
        }
        if (view == send) {
            new async().execute();
        }
    }*/

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        cameraHandler.onResult(requestCode, resultCode, data);
        Log.v("", "code = > " + requestCode);
    }
    // this is used to show diologue
    private void showDialog() {
        if (!pDialog.isShowing())
            pDialog.show();
    }

    // this is used to hide diologue
    private void hideDialog() {
        if (pDialog.isShowing())
            pDialog.dismiss();
    }

}

我找到了在片段使用中调用图像裁剪的答案

AddImage1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = CropImage.activity()
                        .setAspectRatio(16,9)
                        .getIntent(getContext());

                startActivityForResult(intent, CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE);
            }
        });
在onActivityResult上,必须额外添加一行super.onActivityResultrequestCode、resultCode、data


这对我来说非常有效

我找到了在片段使用中调用图像裁剪的答案

AddImage1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = CropImage.activity()
                        .setAspectRatio(16,9)
                        .getIntent(getContext());

                startActivityForResult(intent, CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE);
            }
        });
在onActivityResult上,必须额外添加一行super.onActivityResultrequestCode、resultCode、data

这对我来说非常有效

您可以查看官方文档,它说明了如何获取片段上的裁剪Uri。下面是我的代码片段

@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == GALLERY_REQUEST_CODE && resultCode == RESULT_OK){
        Uri imageUri = data.getData();
        CropImage.activity(imageUri)
                .setGuidelines(CropImageView.Guidelines.ON)
                .setAspectRatio(4,4)
//这就是我错过的 .startgetContext,本

    }
    if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
        CropImage.ActivityResult result = CropImage.getActivityResult(data);
        if (resultCode == RESULT_OK) {
            Uri resultUri = result.getUri();
            Log.d("resultUri ->", String.valueOf(resultUri));
            imageViewProfilePicture.setImageURI(resultUri);
            mImageUri = resultUri;
        } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
            Exception error = result.getError();
            Log.d("error", String.valueOf(error));
        }
    }
}
您可以查看官方文档,它说明了如何获取片段上的裁剪Uri。下面是我的代码片段

@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == GALLERY_REQUEST_CODE && resultCode == RESULT_OK){
        Uri imageUri = data.getData();
        CropImage.activity(imageUri)
                .setGuidelines(CropImageView.Guidelines.ON)
                .setAspectRatio(4,4)
//这就是我错过的 .startgetContext,本

    }
    if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
        CropImage.ActivityResult result = CropImage.getActivityResult(data);
        if (resultCode == RESULT_OK) {
            Uri resultUri = result.getUri();
            Log.d("resultUri ->", String.valueOf(resultUri));
            imageViewProfilePicture.setImageURI(resultUri);
            mImageUri = resultUri;
        } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
            Exception error = result.getError();
            Log.d("error", String.valueOf(error));
        }
    }
}

. 有很多。请用一个,谢谢。但我的代码在活动中也运行良好。我正努力在片段中实现这段代码。裁剪选项不提供,也不在imageview中显示捕获的图像。但我的代码在活动中也运行良好-有数千种Android设备型号。你在多少台电脑上测试过你的应用程序?1.2.不要依赖未记录、不受支持和经常不存在的活动。。有很多。请用一个,谢谢。但我的代码在活动中也运行良好。我正努力在片段中实现这段代码。裁剪选项不提供,也不在imageview中显示捕获的图像。但我的代码在活动中也运行良好-有数千种Android设备型号。你在多少台电脑上测试过你的应用程序?1.2.不要依赖未记录、不受支持和经常不存在的活动。您应该使用Log.d而不是Log.e。您应该使用Log.d而不是Log.e。我花了8个小时来查找错误,为什么我的裁剪图像不能在片段中工作。它在添加了这个之后就开始工作了,.startgetActivity,我花了8个小时来查找错误,为什么我的裁剪图像不能在片段中工作。它在添加此、.startgetActivity、此