作物不适合画廊图像工作 [英] Crop does not work for gallery images

查看:141
本文介绍了作物不适合画廊图像工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用下面的code作物从相机和画廊图像:

I am using the following code to crop images from camera and gallery :

private void doCrop() {
    final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();

    Intent intent = new Intent("com.android.camera.action.CROP");
    intent.setType("image/*");

    List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent, 0);

    int size = list.size();

    if (size == 0) {
        Toast.makeText(this, getApplicationContext().getString(R.string.crop_unavailable), Toast.LENGTH_SHORT).show();
        // return
    } else {
        intent.setData(mImageCaptureUri);
        int y = 200;
        if(lastSelect == 1 || lastSelect == 2 || lastSelect == 3 || lastSelect == 4){
            y = (int) (200 * 0.5697329376854599);
        }
        intent.putExtra("outputX", 200);
        intent.putExtra("outputY", y);
        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 = getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo);
                co.icon = 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(getApplicationContext(), cropOptions);

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle(getApplicationContext().getString(R.string.select_crop_app));
            builder.setAdapter(adapter, new DialogInterface.OnClickListener() {

                @Override
                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) {
                        getContentResolver().delete(mImageCaptureUri, null, null);
                        mImageCaptureUri = null;
                    }
                }
            });

            AlertDialog alert = builder.create();

            alert.show();
        }
    }
}

尽管作物从相机中的照片好了,它不画廊图像工作。它总是返回从图库中选择基本画面。

While it crops pictures from camera well, it doesn't work on gallery images. It always returns basic picture selected from gallery.

onActivityResult

if (resultCode != RESULT_OK)
            return;
        switch (requestCode) {
            case PICK_FROM_CAMERA:
                doCrop();
                break;
            case PICK_FROM_FILE:
                mImageCaptureUri = data.getData();
                doCrop();
                break;
            case CROP_FROM_CAMERA:
                Bundle extras = data.getExtras();
                if (extras != null) {
                    photo = extras.getParcelable("data");
//                    imgImage4.setImageBitmap(photo);
                    int w = (int) (UIHelpers.width * 0.15);
                    File f = new File(mImageCaptureUri.getPath());
                    if (f.exists()) {
                    // f.delete();
                    }
                    String imageDir = getRealPathFromURI(mImageCaptureUri);
                            txtSelectLogoNj.setVisibility(View.GONE);
                            rlLogoNj.setVisibility(View.VISIBLE);
                            image5 = imageDir;
                            App.sharedpreferences = getSharedPreferences(App.MyPREFERENCES, Context.MODE_PRIVATE);
                            App.editor = App.sharedpreferences.edit();
                            App.editor.putString("IMAGE5", imageDir);
                            App.editor.commit();
                    }
                }
                break;
        }

如何解决呢?

How do I fix it?

推荐答案

试试这个工作code

Try this Working code

Buttonclick拿相机

Buttonclick to take camera

dialog.show();

添加这里面的onCreate()

Add this inside Oncreate()

captureImageInitialization();

试试这个它会工作

try this it will work

// for camera

    private void captureImageInitialization() {
        try {
            /**
             * a selector dialog to display two image source options, from
             * camera ‘Take from camera’ and from existing files ‘Select from
             * gallery’
             */
            final String[] items = new String[] { "Take from camera",
                    "Select from gallery" };
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                    android.R.layout.select_dialog_item, items);
            AlertDialog.Builder builder = new AlertDialog.Builder(this);

            builder.setTitle("Select Image");
            builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int item) { // pick
                                                                        // from
                                                                        // camera
                    if (item == 0) {
                        /**
                         * To take a photo from camera, pass intent action
                         * ‘MediaStore.ACTION_IMAGE_CAPTURE‘ to open the camera
                         * app.
                         */
                        Intent intent = new Intent(
                                MediaStore.ACTION_IMAGE_CAPTURE);

                        /**
                         * Also specify the Uri to save the image on specified
                         * path and file name. Note that this Uri variable also
                         * used by gallery app to hold the selected image path.
                         */
                        mImageCaptureUri = Uri.fromFile(new File(Environment
                                .getExternalStorageDirectory(), "tmp_avatar_"
                                + String.valueOf(System.currentTimeMillis())
                                + ".jpg"));

                        intent.putExtra(
                                android.provider.MediaStore.EXTRA_OUTPUT,
                                mImageCaptureUri);

                        try {
                            intent.putExtra("return-data", true);
                            // intent.putExtra("return-data1", true);

                            startActivityForResult(intent, PICK_FROM_CAMERA);
                            // finish();
                        } catch (ActivityNotFoundException e) {
                            e.printStackTrace();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    } else {
                        // pick from file
                        /**
                         * To select an image from existing files, use
                         * Intent.createChooser to open image chooser. Android
                         * will automatically display a list of supported
                         * applications, such as image gallery or file manager.
                         */
                        /*
                         * Intent intent = new Intent();
                         * 
                         * intent.setType("image/*");
                         * intent.setAction(Intent.ACTION_GET_CONTENT);
                         * 
                         * startActivityForResult(Intent.createChooser(intent,
                         * "Complete action using"), PICK_FROM_FILE);
                         */

                        try {


                            Intent intent = new Intent();
                            intent = new Intent(Intent.ACTION_PICK);
                            intent.setType("*/*");
                            intent.putExtra(
                                    android.provider.MediaStore.EXTRA_OUTPUT,
                                    mImageCaptureUri);
                            startActivityForResult(Intent.createChooser(intent,
                                    "Complete action using"), PICK_FROM_FILE);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }
            });

            dialog = builder.create();

        } catch (Exception e) {

            e.printStackTrace();

        } catch (OutOfMemoryError o) {
            o.printStackTrace();
        }

    }

    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) {
            // new try
            try {

                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;

            } catch (Exception e) {

                e.printStackTrace();

            }

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

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



// Method for Crop
            private void doCrop() {

                try {
                    final ArrayList<CropOption> cropOptions = new ArrayList<CropOption>();
                    /**
                     * Open image crop app by starting an intent
                     * ‘com.android.camera.action.CROP‘.
                     */
                    Intent intent = new Intent("com.android.camera.action.CROP");
                    intent.setType("image/*");

                    /**
                     * Check if there is image cropper app installed.
                     */
                    List<ResolveInfo> list = getPackageManager().queryIntentActivities(
                            intent, 0);

                    int size = list.size();

                    /**
                     * If there is no image cropper app, display warning message
                     */
                    if (size == 0) {

                        Toast.makeText(this, "Can not find image crop app",
                                Toast.LENGTH_SHORT).show();

                        return;
                    } else {
                        /**
                         * Specify the image path, crop dimension and scale
                         */
                        intent.setData(mImageCaptureUri);

                        intent.putExtra("outputX", 300);
                        intent.putExtra("outputY", 300);
                        intent.putExtra("aspectX", 1);
                        intent.putExtra("aspectY", 1);
                        intent.putExtra("scale", true);
                        intent.putExtra("return-data", true);

                        /**
                         * There is posibility when more than one image cropper app
                         * exist, so we have to check for it first. If there is only one
                         * app, open then app.
                         */

                        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 {
                            /**
                             * If there are several app exist, create a custom chooser
                             * to let user selects the app.
                             */
                            for (ResolveInfo res : list) {
                                final CropOption co = new CropOption();

                                co.title = getPackageManager().getApplicationLabel(
                                        res.activityInfo.applicationInfo);
                                co.icon = 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(
                                    getApplicationContext(), cropOptions);

                            AlertDialog.Builder builder = new AlertDialog.Builder(this);
                            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) {
                                        getContentResolver().delete(mImageCaptureUri,
                                                null, null);
                                        mImageCaptureUri = null;
                                    }
                                }
                            });

                            AlertDialog alert = builder.create();

                            alert.show();
                        }
                    }
                }

                catch (Exception e) {

                    Log.e("Error", "ERROR IN CODE:" + e.toString());

                    e.printStackTrace();

                }
            }

onActivityResult:

      if (requestCode == PICK_FROM_CAMERA) {

                doCrop();

            }
    else if (requestCode == PICK_FROM_FILE) {
                mImageCaptureUri = intent.getData();

                doCrop();
            }       
else if (requestCode == CROP_FROM_CAMERA) {

                Bundle extras = intent.getExtras();
                /**
                 * After cropping the image, get the bitmap of the cropped image and
                 * display it on imageview.
                 */


                if (extras != null) {

                    Bitmap photo = extras.getParcelable("data");
                    // Camera Output



                        viewImage.setImageBitmap(photo);

                        ContextWrapper cw = new ContextWrapper(getApplicationContext());
                        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
                        String imageFileName = "JPEG_" + timeStamp + "_";
                        File directory1 = cw.getDir("Picture",Context.MODE_PRIVATE);
                        File mypath1 = new File(directory1, imageFileName + ".png");
                        picturepath = mypath1.toString();

                        // FileOutputStream fos = null;
                        try {
                            // fos = openFileOutput(filename, Context.MODE_PRIVATE);
                            System.out.println("mypath = " + mypath1);
                            fos = new FileOutputStream(mypath1);

                            // Use the compress method on the BitMap object to write
                            // image to the OutputStream
                            photo.compress(Bitmap.CompressFormat.PNG, 100, fos);

                            try {
                                fos.flush();
                                fos.close();


                            } catch (IOException e1) {

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

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



                }
            }

这篇关于作物不适合画廊图像工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆