android KitKat image Crop

2019-03-03 19:57发布

问题:

I am passing image url to the following method

private void performCrop(Uri imageUri){
        try {
            Intent intent = new Intent("com.android.camera.action.CROP"); 
          //  intent.setType("image/*");
            intent.setDataAndType(imageUri, "image/*");
            List<ResolveInfo> list = getActivity().getPackageManager().queryIntentActivities( intent, 0 );
            int size = list.size();

            if (size >= 0) {
                intent.setData(imageUri);        
                intent.putExtra("crop", "true");
                intent.putExtra("aspectX", 0);
                intent.putExtra("aspectY", 0);
                intent.putExtra("outputX", 150);
                intent.putExtra("outputY", 150);
                intent.putExtra("scale", true);
                intent.putExtra("scaleUpIfNeeded", true);
                intent.putExtra("return-data", true);
                Intent i = new Intent(intent);

                ResolveInfo res = list.get(0);

                i.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
                System.out.println("before startActivityForResult");
                try{
                startActivityForResult(i, 2);  
                }catch(Exception e){
                    e.printStackTrace();
                }
             } 

        }
        catch(ActivityNotFoundException anfe){
            String errorMessage = "Whoops - your device doesn't support the crop action!";
            //Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
            //toast.show();
        }
    }

some of images are cropped but some image are not. When I crop image then my app's activity is closed and application starts it's previous or launcher activity so what is the problem??

the main issue is I am not getting any warning or error in log cat, and when I debug it the the till "System.out.println("before startActivityForResult");" the program excutes, that means it does not goes in or calling onActivityResult().

here is onActivityResult method

 @Override
   public void onActivityResult(int requestCode, int resultCode, Intent data) {
      // TODO Auto-generated method stub
      super.onActivityResult(requestCode, resultCode, data);




if(requestCode ==2 && resultCode == getActivity().RESULT_OK){
            System.out.println("inside logic...");
            try{
                if (data != null) {

               //  get the returned data
                    Bundle extras = data.getExtras();
                    // get the cropped bitmap
                    Bitmap bmp = extras.getParcelable("data");

                        imageView.setImageBitmap(bmp);


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

     }
    }

回答1:

this code works successfully for me.try it

private static final int CAMERA_REQUEST = 1;
public static final int MEDIA_TYPE_IMAGE = 1;
final int PIC_CROP = 12;
Button btnCamera;
ImageView iv;
Uri picUri;
static File mediaFile, sendFile;



btnCamera.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            onImgProfile();
        }
    });



void onImgProfile() {
    Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    picUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

    captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, picUri);

    startActivityForResult(captureIntent, CAMERA_REQUEST);
}


private Uri getOutputMediaFileUri(int type) {
    return Uri.fromFile(getOutputMediaFile(type));
}

private File getOutputMediaFile(int type) {

    File mediaStorageDir = new File(
            Environment.getExternalStorageDirectory(), "MyCameraApp");

    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Log.d("MyCameraApp", "failed to create directory");
            return null;
        }
    }

    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
            .format(new Date());

    if (type == MEDIA_TYPE_IMAGE) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "IMG_" + timeStamp + ".jpg");
    } else {
        return null;
    }

    return mediaFile;
}



    @SuppressWarnings("unchecked")
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == CAMERA_REQUEST) {
        // if (Build.VERSION.SDK_INT < 19) {
        try {
            if (mediaFile.exists()) {
                performCrop();
                // new SavePhotoData().execute();
            }

        } catch (Exception e) {
            // TODO: handle exception

        }
        // }

    } else if (requestCode == 11) {

        try {
            picUri = data.getData();
            Log.i("uri", "" + picUri);
            performCrop();
        } catch (Exception e) {
            // TODO: handle exception

        }

    } else if (requestCode == PIC_CROP) {
        // get the returned data

        try {
            Bundle extras = data.getExtras();

            // get the cropped bitmap
            Bitmap thePic = extras.getParcelable("data");
            // retrieve a reference to the ImageView

            // display the returned cropped image
            iv.setImageBitmap(thePic);

            File mediaStorageDir = new File(
                    Environment.getExternalStorageDirectory(),
                    "MyCameraApp");

            if (!mediaStorageDir.exists()) {
                if (!mediaStorageDir.mkdirs()) {
                    Log.d("MyCameraApp", "failed to create directory");

                }
            }

            // Create a media file name
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
                    .format(new Date());

            sendFile = new File(mediaStorageDir.getPath() + File.separator
                    + "IMG_" + timeStamp + ".png");

            FileOutputStream fOut = new FileOutputStream(sendFile);

            thePic.compress(Bitmap.CompressFormat.PNG, 85, fOut);
            fOut.flush();
            fOut.close();

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

        }
    }

    if (resultCode == 3) {
        Bundle b = data.getExtras();
        b.getString("msg");
    }
};



private void performCrop() {
    // take care of exceptions
    try {
        // call the standard crop action intent (the user device may not
        // support it)
        try {
            Intent cropIntent = new Intent("com.android.camera.action.CROP");
            // indicate image type and Uri
            cropIntent.setDataAndType(picUri, "image/*");
            // set crop properties
            cropIntent.putExtra("crop", "true");
            // indicate aspect of desired crop
            cropIntent.putExtra("aspectX", 1);
            cropIntent.putExtra("aspectY", 1);
            // indicate output X and Y
            cropIntent.putExtra("outputX", 256);
            cropIntent.putExtra("outputY", 256);
            // retrieve data on return
            cropIntent.putExtra("return-data", true);
            // start the activity - we handle returning in onActivityResult
            startActivityForResult(cropIntent, PIC_CROP);
        } catch (Exception e) {
            // TODO: handle exception
        }
    }
    // respond to users whose devices do not support the crop action
    catch (ActivityNotFoundException anfe) {
        // display an error message
        String errorMessage = "Whoops - your device doesn't support the crop action!";
        Toast toast = Toast.makeText(getApplicationContext(), errorMessage,
                Toast.LENGTH_SHORT);
        toast.show();
    }
}

this code works for not only kitkat but all cersion of android



回答2:

Android all devices does not have a cropping intent according @CommonsWare http://commonsware.com/blog/2013/01/23/no-android-does-not-have-crop-intent.html

so better is to use libraries

some of them are:

https://github.com/jdamcd/android-crop

https://github.com/IsseiAoki/SimpleCropView

https://android-arsenal.com/details/1/3054