【问题标题】:Android crop image after taken拍摄后的Android裁剪图像
【发布时间】:2013-01-25 09:42:31
【问题描述】:

我试图让用户在拍摄/从图库中选择后裁剪图像。现在,从画廊作品而不是相机中选择后的裁剪。以下是我的代码,我没有收到任何错误消息。我们关注了http://mobile.tutsplus.com/tutorials/android/capture-and-crop-an-image-with-the-device-camera/

//Camera button  clicked
    public void camera_click(View view) {
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        cameraIntent.putExtra("return-data", true);
        startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);

    } 
    //Result of camera capture
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
                 //camera
            if (requestCode == CAMERA_PIC_REQUEST) {

                mImageCaptureUri = data.getData();
                performCrop();
            }
            if (requestCode == PIC_CROP) {
                //get the returned data
                try{
                Bundle extras = data.getExtras();
//get the cropped bitmap
                thumbnail = extras.getParcelable("data");
                //retrieve a reference to the ImageView
                ImageView image = (ImageView) findViewById(R.id.test_image);
//display the returned cropped image
                image.setImageBitmap(thumbnail);
                TextView imgTv = (TextView) findViewById(R.id.imageInfo);
                String desc = imgTv.getText().toString();
                if (desc.equalsIgnoreCase("")) {
                    String errorMessage = "Please enter a description before submitting a photo.";
                    Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
                    toast.show();
                } else {

                }
                }
                catch(Exception ex)
                {
                    Log.i("err", ex.getMessage());
                }
            }
                 //gallery selected
            if (requestCode == SELECT_PHOTO) {
                if (data != null) {

                    Cursor cursor = getContentResolver().query(data.getData(), null, null, null, null);
                    cursor.moveToFirst();  //if not doing this, 01-22 19:17:04.564: ERROR/AndroidRuntime(26264): Caused by: android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
                    int idx = cursor.getColumnIndex(ImageColumns.DATA);
                    String fileSrc = cursor.getString(idx);
                    thumbnail = BitmapFactory.decodeFile(fileSrc); //load preview image
                    thumbnail = android.graphics.Bitmap.createScaledBitmap(thumbnail, 100, 100, true);
                    //   ImageView image = (ImageView) findViewById(R.id.test_image);
                    // image.setImageBitmap(thumbnail);
                    ImageButton cam = (ImageButton) findViewById(R.id.camera);
                    //    cam.setVisibility(View.INVISIBLE);
                    ImageButton gal = (ImageButton) findViewById(R.id.gallery);
                    mImageCaptureUri = data.getData();
                    //  gal.setVisibility(View.INVISIBLE);
                    performCrop();

                } else {
                    //Log.d(LOG_TAG, "idButSelPic Photopicker canceled");
                    // m_Tv.setText("Image selection canceled!");
                }

            }
        }
    }//end onactivity results

    //method to luanch crop image
private void performCrop() {
    try {
        //call the standard crop action intent (the user device may not support it)
        Intent cropIntent = new Intent("com.android.camera.action.CROP");


        cropIntent.setDataAndType(mImageCaptureUri, "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 (ActivityNotFoundException anfe) {
        //display an error message
        Log.i("err", anfe.getLocalizedMessage());
        String errorMessage = "Your device doesn't support the crop action!";
        Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
        toast.show();
        Intent myIntent = new Intent();
        startActivityForResult(myIntent, PIC_CROP);
    }
}

【问题讨论】:

    标签: android android-gallery


    【解决方案1】:

    这行可能会给你这个问题:

    mImageCaptureUri = data.getData(); 
    

    删除并查看。

    如果没有,我可以给你一个工作代码。

    工作示例: 还包括这个库:https://github.com/lvillani/android-cropimage

    @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            // TODO Auto-generated method stub
             switch (requestCode) {
                case PICK_FROM_CAMERA:
    
    
                        doCrop();
    
    
    
                    break;
    
                case PICK_FROM_FILE: 
                    if(data != null){
                    mImageCaptureUri = data.getData();
    
                    doCrop();
                    }
                    break;          
    
                case CROP_FROM_CAMERA:     
                    if(data != null){
                    Bundle extras = data.getExtras();
    
                    if (extras != null) {               
                        Bitmap photo = extras.getParcelable("data");
    
                        imagebutton.setImageBitmap(photo);
                        imagebutton.setScaleType(ScaleType.FIT_XY);
    
    
                    }
    
                    File f = new File(mImageCaptureUri.getPath());            
    
                    if (f.exists()) f.delete();
                    }
                    break;
    
            }
        }
    
        private void doCrop() {
            // TODO Auto-generated method stub
            final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();
    
            Intent intent = new Intent("com.android.camera.action.CROP");
    //        intent.setClassName("com.android.camera", "com.android.camera.CropImage");
            intent.setType("image/*");
    
            List<ResolveInfo> list = getActivity().getPackageManager().queryIntentActivities( intent, 0 );
    
            int size = list.size();
    
            if (size == 0) {
                Toast.makeText(getActivity(), "Can not find image crop app", Toast.LENGTH_SHORT).show();
    
                return;
            } else {
                intent.setData(mImageCaptureUri);
    
                intent.putExtra("outputX", 200);
                intent.putExtra("outputY", 200);
                intent.putExtra("aspectX", 1);
                intent.putExtra("aspectY", 1);
                intent.putExtra("scale", true);
                intent.putExtra("return-data", true);
    
                if (size == 1) {
                    Intent i        = new Intent(intent);
                    ResolveInfo res = list.get(0);
    
                    i.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
    
                    startActivityForResult(i, CROP_FROM_CAMERA);
                } else {
                    for (ResolveInfo res : list) {
                        final CropOption co = new CropOption();
    
                        co.title    = getActivity().getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo);
                        co.icon     = getActivity().getPackageManager().getApplicationIcon(res.activityInfo.applicationInfo);
                        co.appIntent= new Intent(intent);
    
                        co.appIntent.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
    
                        cropOptions.add(co);
                    }
    
                    CropOptionAdapter adapter = new CropOptionAdapter(getActivity(), cropOptions);
    
                    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                    builder.setTitle("Choose Crop App");
                    builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
                        public void onClick( DialogInterface dialog, int item ) {
                            startActivityForResult( cropOptions.get(item).appIntent, CROP_FROM_CAMERA);
                        }
                    });
    
                    builder.setOnCancelListener( new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel( DialogInterface dialog ) {
    
                            if (mImageCaptureUri != null ) {
                                getActivity().getContentResolver().delete(mImageCaptureUri, null, null );
                                mImageCaptureUri = null;
                            }
                        }
                    } );
    
                    AlertDialog alert = builder.create();
    
                    alert.show();
                }
            }
        }
    

    CropOption 类:

    public class CropOption {
        public CharSequence title;
        public Drawable icon;
        public Intent appIntent;
    }
    

    CropOptionAdapter:

    public class CropOptionAdapter extends ArrayAdapter<CropOption> {
        private ArrayList<CropOption> mOptions;
        private LayoutInflater mInflater;
    
        public CropOptionAdapter(Context context, ArrayList<CropOption> options) {
            super(context, R.layout.crop_selector, options);
    
            mOptions    = options;
    
            mInflater   = LayoutInflater.from(context);
        }
    
        @Override
        public View getView(int position, View convertView, ViewGroup group) {
            if (convertView == null)
                convertView = mInflater.inflate(R.layout.crop_selector, null);
    
            CropOption item = mOptions.get(position);
    
            if (item != null) {
                ((ImageView) convertView.findViewById(R.id.iv_icon)).setImageDrawable(item.icon);
                ((TextView) convertView.findViewById(R.id.tv_name)).setText(item.title);
    
                return convertView;
            }
    
            return null;
        }
    }
    

    【讨论】:

    • 看看能不能看懂。
    • 你也可以发布 doCrop 方法吗?
    • 感谢您的示例代码。请问“CropOption”是不是你写的附加类?
    • 不抱歉,它来自裁剪图像库,请查看答案中的链接。
    • 库中没有 CropOption 类
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多