如何得到正确的路径裁剪后的图像?路径、图像、正确

由网友(21.年少纵马且歌)分享简介:我要裁剪的捕获/选择的图像并把它上传到服务器。 什么问题我面对:裁剪图像后,我没有得到实际路径为裁剪图像。我做了以下的方法我code。我是正确croping的形象也一切正常,但在这里是ImageView的不显示裁剪后的图像的原始图像代替。 然而,当我已经赚得了位图位图照片= extras.getParcelable(数...

我要裁剪的捕获/选择的图像并把它上传到服务器。

什么问题我面对:裁剪图像后,我没有得到实际路径为裁剪图像。我做了以下的方法我code。我是正确croping的形象也一切正常,但在这里是ImageView的不显示裁剪后的图像的原始图像代替。

然而,当我已经赚得了位图位图照片= extras.getParcelable(数据); onActivityResult()我得到裁剪的图像显示在imageview.but没有得到能够绝对路径的裁剪图像。

任何人都可以请指导我在哪里,我缺乏。我已经尝试了许多SO联系,但没能得到确切的解决方案,我的问题。

下面是我的code:

 公共类MainActivity延伸活动{
    私人乌里mImageCaptureUri;
    私人ImageView的mImageView;

    私有静态最终诠释PICK_FROM_CAMERA = 1;
    私有静态最终诠释CROP_FROM_CAMERA = 2;
    私有静态最终诠释PICK_FROM_FILE = 3;

    私人字符串selectedImagePath =;
    布尔GallaryPhotoSelected = FALSE;

    公共静态字符串Finalmedia =;

    @覆盖
    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);

        的setContentView(R.layout.main);

        最终的String []项目=新的String [] {从相机拿,
                从库中选择};
        ArrayAdapter<字符串>适配器=新的ArrayAdapter<字符串>(这一点,
                android.R.layout.select_dialog_item,项目);
        AlertDialog.Builder建设者=新AlertDialog.Builder(本);

        builder.setTitle(选择图片);
        builder.setAdapter(适配器,新DialogInterface.OnClickListener(){
            公共无效的onClick(DialogInterface对话,诠释项){//挑选
                                                                    // 相机
                如果(项目== 0){
                    意向意图=新的意图(MediaStore.ACTION_IM​​AGE_CAPTURE);

                    mImageCaptureUri = Uri.fromFile(新文件(环境
                            .getExternalStorageDirectory(),tmp_avatar_
                            +将String.valueOf(System.currentTimeMillis的())
                            +.JPG));

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

                    尝试 {
                        intent.putExtra(回归数据,真正的);

                        startActivityForResult(意向,PICK_FROM_CAMERA);
                    }赶上(ActivityNotFoundException E){
                        e.printStackTrace();
                    }
                }其他{//挑选文件
                    意向意图=新的意图();

                    intent.setType(图像/ *);
                    intent.setAction(Intent.ACTION_GET_CONTENT);

                    startActivityForResult(Intent.createChooser(意向,
                            完整的行动使用),PICK_FROM_FILE);
                }
            }
        });

        最后AlertDialog对话框= builder.create();

        Button按钮=(按钮)findViewById(R.id.btn_crop);
        mImageView =(ImageView的)findViewById(R.id.iv_photo);

        button.setOnClickListener(新View.OnClickListener(){
            @覆盖
            公共无效的onClick(视图v){
                dialog.show();
            }
        });
    }

    @覆盖
    保护无效onActivityResult(INT申请code,INT结果code,意图数据){
        如果(结果code!= RESULT_OK)
            返回;

        开关(要求code){
        案例PICK_FROM_CAMERA:
            doCrop();

            打破;

        案例PICK_FROM_FILE:
            mImageCaptureUri = data.getData();
            Log.i(TAG,
                    经过裁剪mImageCaptureUri+ mImageCaptureUri.getPath());
            GallaryPhotoSelected = TRUE;
            doCrop();

            打破;

        案例CROP_FROM_CAMERA:
            捆绑额外= data.getExtras();

            selectedImagePath = mImageCaptureUri.getPath();

            Log.i(TAG,作物selectedImagePath后+ selectedImagePath);

            如果(GallaryPhotoSelected){
                selectedImagePath = getRealPathFromURI(mImageCaptureUri);
                Log.i(TAG,绝对路径+ selectedImagePath);
                GallaryPhotoSelected = TRUE;
            }

            Finalmedia = selectedImagePath;

            Log.i(TAG,Finalmedia路径+ Finalmedia);

            如果(临时演员!= NULL){
                位图照片= extras.getParcelable(数据);

                位图BM = BitmapFactory.de codeFILE(Finalmedia);

                mImageView.setImageBitmap(BM);
            }

            //文件F =新的文件(mImageCaptureUri.getPath());
            //
            //如果(f.exists())f.delete();

            打破;

        }
    }

    公共静态位图德codeFILE(字符串路径){
        INT方向;
        尝试 {
            如果(路径== NULL){
                返回null;
            }
            //德code图像尺寸
            BitmapFactory.Options O =新BitmapFactory.Options();
            o.inJustDe codeBounds = TRUE;
            //找到正确的比例值。它应该是2的幂。
            最终诠释REQUIRED_SIZE = 70;
            INT width_tmp = o.outWidth,height_tmp = o.outHeight;
            int标= 2;
            //而(真){
            //如果(width_tmp / 2'; REQUIRED_SIZE
            // || height_tmp / 2版; REQUIRED_SIZE)
            // 打破;
            // width_tmp / = 2;
            // height_tmp / = 2;
            //规模++;
            //}
            //德code与inSampleSize
            BitmapFactory.Options O2 =新BitmapFactory.Options();
            o2.inSampleSize =规模;
            位图BM = BitmapFactory.de codeFILE(路径,O2);
            点阵位图= BM;

            ExifInterface EXIF​​ =新ExifInterface(路径);

            方向= EXIF
                    .getAttributeInt(ExifInterface.TAG_ORIENTATION,1);

            Log.e(ExifInteface .........,旋转=+方向);

            // exif.setAttribute(ExifInterface.ORIENTATION_ROTATE_90,90);

            Log.e(方向,+方向);
            矩阵M =新的Matrix();

            如果((取向== ExifInterface.ORIENTATION_ROTATE_180)){
                m.postRotate(180);
                // m.postScale((浮点)bm.getWidth(),(浮动)bm.getHeight());
                //如果(米。preRotate(90)){
                Log.e(定向,+方向);
                位图= Bitmap.createBitmap(宽多重峰,0,0,bm.getWidth(),
                        bm.getHeight(),男,真正的);
                返回的位图;
            }否则,如果(定向== ExifInterface.ORIENTATION_ROTATE_90){
                m.postRotate(90);
                Log.e(定向,+方向);
                位图= Bitmap.createBitmap(宽多重峰,0,0,bm.getWidth(),
                        bm.getHeight(),男,真正的);
                返回的位图;
            }否则,如果(定向== ExifInterface.ORIENTATION_ROTATE_270){
                m.postRotate(270);
                Log.e(定向,+方向);
                位图= Bitmap.createBitmap(宽多重峰,0,0,bm.getWidth(),
                        bm.getHeight(),男,真正的);
                返回的位图;
            }
            返回的位图;
        }赶上(例外五){
            返回null;
        }

    }

    公共字符串getRealPathFromURI(URI contentUri){
        的String []凸出= {MediaStore.Images.Media.DATA};
        光标光标= managedQuery(contentUri,凸出,NULL,NULL,NULL);
        INT与Column_Index =光标
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        返回cursor.getString(Column_Index中);
    }

    私人无效doCrop(){
        最后的ArrayList< CropOption> cropOptions =新的ArrayList< CropOption>();

        意向意图=新的意图(com.android.camera.action.CROP);
        intent.setType(图像/ *);

        名单< ResolveInfo>表= getPackageManager()。queryIntentActivities(
                意图,0);

        INT大小=则为list.size();

        如果(大小== 0){
            Toast.makeText(这一点,找不到图像裁剪的应用程序,
                    Toast.LENGTH_SHORT).show();

            返回;
        } 其他 {
            intent.setData(mImageCaptureUri);

            intent.putExtra(outputX,200);
            intent.putExtra(outputY,200);
            intent.putExtra(aspectX,1);
            intent.putExtra(aspectY,1);
            intent.putExtra(规模化,真正的);
            intent.putExtra(回归数据,真正的);

            如果(尺寸== 1){
                意图I =新的意向(意向);
                ResolveInfo解析度= list.get(0);

                i.setComponent(新的组件名(res.activityInfo.packageName,
                        res.activityInfo.name));

                startActivityForResult(ⅰ,CROP_FROM_CAMERA);
            } 其他 {
                对于(ResolveInfo RES:名单){
                    最后CropOption合作=新CropOption();

                    co.title = getPackageManager()。getApplicationLabel(
                            res.activityInfo.applicationInfo);
                    co.icon = getPackageManager()。getApplicationIcon(
                            res.activityInfo.applicationInfo);
                    co.appIntent =新的意图(意图);

                    co.appIntent
                            .setComponent(新的组件名(
                                    res.activityInfo.packageName,
                                    res.activityInfo.name));

                    cropOptions.add(共);
                }

                CropOptionAdapter适配器=新CropOptionAdapter(
                        getApplicationContext(),cropOptions);

                AlertDialog.Builder建设者=新AlertDialog.Builder(本);
                builder.setTitle(选择作物应用程序);
                builder.setAdapter(适配器,
                        新DialogInterface.OnClickListener(){
                            公共无效的onClick(DialogInterface对话,诠释项){
                                startActivityForResult(
                                        cropOptions.get(项目).appIntent,
                                        CROP_FROM_CAMERA);
                            }
                        });

                builder.setOnCancelListener(新DialogInterface.OnCancelListener(){
                    @覆盖
                    公共无效OnCancel的(DialogInterface对话){

                        如果(mImageCaptureUri!= NULL){
                            getContentResolver()。删除(mImageCaptureUri,空,
                                    空值);
                            mImageCaptureUri = NULL;
                        }
                    }
                });

                AlertDialog警报= builder.create();

                alert.show();
            }
        }
    }
}
 

解决方案

花费大量时间在这个问题上,我终于使工作由下面的方式,如果有一个人是一种在将来出现此问题后。

 公共类MainActivity延伸活动{
    私人乌里mImageCaptureUri;
    私人ImageView的mImageView;

    私有静态最终诠释PICK_FROM_CAMERA = 1;
    私有静态最终诠释CROP_FROM_CAMERA = 2;
    私有静态最终诠释PICK_FROM_FILE = 3;

    私人字符串selectedImagePath =;
    布尔GallaryPhotoSelected = FALSE;

    公共静态字符串Finalmedia =;

    @覆盖
    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);

        的setContentView(R.layout.main);

        最终的String []项目=新的String [] {从相机拿,
                从库中选择};
        ArrayAdapter<字符串>适配器=新的ArrayAdapter<字符串>(这一点,
                android.R.layout.select_dialog_item,项目);
        AlertDialog.Builder建设者=新AlertDialog.Builder(本);

        builder.setTitle(选择图片);
        builder.setAdapter(适配器,新DialogInterface.OnClickListener(){
            公共无效的onClick(DialogInterface对话,诠释项){//挑选
                                                                    // 相机
                如果(项目== 0){
                    串storageState = Environment.getExternalStorageState();

                    如果(storageState.equals(Environment.MEDIA_MOUNTED)){
                        意向意图=新的意图(
                                MediaStore.ACTION_IM​​AGE_CAPTURE);
                        // intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
                        // mImageCaptureUri);
                        //如果(hasImageCaptureBug()){

                        字符串路径= Environment.getExternalStorageDirectory()
                                .getName()
                                +即File.separatorChar
                                + System.currentTimeMillis的()+.JPG;
                        档案文件=新的文件(路径);
                        // mImageCaptureUri = Uri.fromFile(新文件(
                        // Environment.getExternalStorageDirectory(),
                        //tmp_avatar_
                        // +将String.valueOf(系统
                        // .currentTimeMillis())
                        // +.JPG));
                        Log.i(TAG,最后的道路+路径);
                        尝试 {
                            如果(file.exists()== FALSE){
                                file.getParentFile()mkdirs()。
                                file.createNewFile();
                            }

                        }赶上(IOException异常E){
                            Log.e(TAG,无法创建文件,E);
                        }
                        mImageCaptureUri = Uri.fromFile(文件);
                        intent.putExtra(
                                android.provider.MediaStore.EXTRA_OUTPUT,
                                mImageCaptureUri);
                        // } 其他 {
                        // intent.putExtra(
                        // android.provider.MediaStore.EXTRA_OUTPUT,
                        // android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        //}

                        尝试 {
                            // intent.putExtra(返回数据,真正的);
                            startActivityForResult(意向,PICK_FROM_CAMERA);
                        }赶上(ActivityNotFoundException E){
                            e.printStackTrace();
                        }
                    } 其他 {
                        新AlertDialog.Builder(MainActivity.this)
                                .setMessage(
                                        外部的StoreAge(SD卡)需要ñ n目前的状态。
                                                + storageState)
                                .setCancelable(真).create()显示()。
                    }

                }其他{//挑选文件
                    意向意图=新的意图();

                    intent.setType(图像/ *);
                    intent.setAction(Intent.ACTION_GET_CONTENT);

                    startActivityForResult(Intent.createChooser(意向,
                            完整的行动使用),PICK_FROM_FILE);
                }
            }
        });

        最后AlertDialog对话框= builder.create();

        Button按钮=(按钮)findViewById(R.id.btn_crop);
        mImageView =(ImageView的)findViewById(R.id.iv_photo);

        button.setOnClickListener(新View.OnClickListener(){
            @覆盖
            公共无效的onClick(视图v){
                dialog.show();
            }
        });
    }

    公共布尔hasImageCaptureBug(){

        有错误已知设备//名单
        ArrayList的<字符串>设备=新的ArrayList<字符串>();
        devices.add(Android的devphone1 / dream_devphone /梦);
        devices.add(通用/ SDK /通用);
        devices.add(沃达丰/ vfpioneer /蓝宝石);
        devices.add(tmobile的/基拉/梦);
        devices.add(Verizon公司/田鼠/肖尔斯);
        devices.add(google_ion / google_ion /蓝宝石);

        返回devices.contains(android.os.Build.BRAND +/
                + android.os.Build.PRODUCT +/+ android.os.Build.DEVICE);

    }

    @覆盖
    保护无效onActivityResult(INT申请code,INT结果code,意图数据){
        如果(结果code!= RESULT_OK)
            返回;

        开关(要求code){
        案例PICK_FROM_CAMERA:
            Log.i(TAG,内部PICK_FROM_CAMERA);
            // mImageCaptureUri = data.getData();
            //位图BM1 =(位图)data.getExtras()获得(数据);
            // mImageView.setImageBitmap(BM1);
            //捆绑extras1 = data.getExtras();
            //位图BM1 =(位图)extras1.get(数据);
            // mImageView.setImageBitmap(BM1);

            / *
             *尝试{如果(hasImageCaptureBug()){Log.i(TAG,内部错误);
             * selectedImagePath =将String.valueOf(系统.currentTimeMillis())+
             *.JPG;文件F1 =新的文件(
             * Environment.getExternalStorageDirectory(),selectedImagePath);
             *尝试{mImageCaptureUri =开放的我们
             * .parse(android.provider.MediaStore.Images.Media
             * .insertImage(getContentResolver(),fi.getAbsolutePath(),空,
             * 空值));如果(!fi.delete()){Log.i(logMarker,
             *无法删除+ FI); }}赶上(FileNotFoundException异常E){
             * e.printStackTrace(); }}其他{mImageCaptureUri =
             * data.getData(); }}赶上(例外五){Log.i(TAG,
             *内部错误); selectedImagePath =
             *将String.valueOf(System.currentTimeMillis的())+.JPG;文件F1 =
             *新的文件(Environment.getExternalStorageDirectory()
             * selectedImagePath);尝试{mImageCaptureUri =开放的我们
             * .parse(android.provider.MediaStore.Images.Media
             * .insertImage(getContentResolver(),fi.getAbsolutePath(),空,
             * 空值));如果(!fi.delete()){Log.i(logMarker,
             *无法删除+ FI); }}赶上(FileNotFoundException异常E1){
             * e1.printStackTrace(); }}
             * /

            字符串路径= mImageCaptureUri.getPath();
            Log.i(TAG,
                    !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!后捕捉路径
                            +路径);

            doCrop();

            打破;

        案例PICK_FROM_FILE:
            mImageCaptureUri = data.getData();
            Log.i(TAG,
                    经过裁剪mImageCaptureUri+ mImageCaptureUri.getPath());
            GallaryPhotoSelected = TRUE;
            doCrop();

            打破;

        案例CROP_FROM_CAMERA:
            捆绑额外= data.getExtras();

            selectedImagePath = mImageCaptureUri.getPath();

            Log.i(TAG,作物selectedImagePath后+ selectedImagePath);

            如果(GallaryPhotoSelected){
                selectedImagePath = getRealPathFromURI(mImageCaptureUri);
                Log.i(TAG,绝对路径+ selectedImagePath);
                GallaryPhotoSelected = TRUE;
            }

            Finalmedia = selectedImagePath;

            如果(临时演员!= NULL){
                //位图的照片= extras.getParcelable(数据);
                Log.i(TAG,内部特+ selectedImagePath);
                位图照片=(位图)extras.get(数据);

                selectedImagePath =将String.valueOf(System.currentTimeMillis的())
                        +.JPG;

                Log.i(TAG,文件之前,新selectedImagePath
                        + selectedImagePath);

                档案文件=新的文件(Environment.getExternalStorageDirectory()
                        selectedImagePath);

                尝试 {
                    file.createNewFile();
                    FileOutputStream中FOS =新的FileOutputStream(文件);
                    photo.com preSS(Bitmap.Com pressFormat.PNG,95,FOS);
                }赶上(IOException异常E){
                    // TODO自动生成的catch块
                    Toast.makeText(这一点,
                            对不起,相机损毁,请报告崩溃A.
                            Toast.LENGTH_LONG).show();
                }

                selectedImagePath = Environment.getExternalStorageDirectory()
                        +/+ selectedImagePath;
                Log.i(TAG,文件后创建+ selectedImagePath);

                位图BM =去codeFILE(selectedImagePath);
                mImageView.setImageBitmap(BM);
            }

            / *
             *文件F =新的文件(mImageCaptureUri.getPath());
             *
             *如果(f.exists())f.delete();
             * /

            打破;

        }
    }

    公共静态位图德codeFILE(字符串路径){
        INT方向;
        尝试 {
            如果(路径== NULL){
                返回null;
            }
            //德code图像尺寸
            BitmapFactory.Options O =新BitmapFactory.Options();
            o.inJustDe codeBounds = TRUE;
            //找到正确的比例值。它应该是2的幂。
            最终诠释REQUIRED_SIZE = 70;
            INT width_tmp = o.outWidth,height_tmp = o.outHeight;
            int标= 1;
            //而(真){
            //如果(width_tmp / 2'; REQUIRED_SIZE
            // || height_tmp / 2版; REQUIRED_SIZE)
            // 打破;
            // width_tmp / = 2;
            // height_tmp / = 2;
            //规模++;
            //}
            //德code与inSampleSize
            BitmapFactory.Options O2 =新BitmapFactory.Options();
            o2.inSampleSize =规模;
            位图BM = BitmapFactory.de codeFILE(路径,O2);
            点阵位图= BM;

            ExifInterface EXIF​​ =新ExifInterface(路径);

            方向= EXIF
                    .getAttributeInt(ExifInterface.TAG_ORIENTATION,1);

            Log.e(ExifInteface .........,旋转=+方向);

            // exif.setAttribute(ExifInterface.ORIENTATION_ROTATE_90,90);

            Log.e(方向,+方向);
            矩阵M =新的Matrix();

            如果((取向== ExifInterface.ORIENTATION_ROTATE_180)){
                m.postRotate(180);
                // m.postScale((浮点)bm.getWidth(),(浮动)bm.getHeight());
                //如果(米。preRotate(90)){
                Log.e(定向,+方向);
                位图= Bitmap.createBitmap(宽多重峰,0,0,bm.getWidth(),
                        bm.getHeight(),男,真正的);
                返回的位图;
            }否则,如果(定向== ExifInterface.ORIENTATION_ROTATE_90){
                m.postRotate(90);
                Log.e(定向,+方向);
                位图= Bitmap.createBitmap(宽多重峰,0,0,bm.getWidth(),
                        bm.getHeight(),男,真正的);
                返回的位图;
            }否则,如果(定向== ExifInterface.ORIENTATION_ROTATE_270){
                m.postRotate(270);
                Log.e(定向,+方向);
                位图= Bitmap.createBitmap(宽多重峰,0,0,bm.getWidth(),
                        bm.getHeight(),男,真正的);
                返回的位图;
            }
            返回的位图;
        }赶上(例外五){
            返回null;
        }

    }

    公共字符串getRealPathFromURI(URI contentUri){
        的String []凸出= {MediaStore.Images.Media.DATA};
        光标光标= managedQuery(contentUri,凸出,NULL,NULL,NULL);
        INT与Column_Index =光标
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        返回cursor.getString(Column_Index中);
    }

    私人无效doCrop(){
        最后的ArrayList< CropOption> cropOptions =新的ArrayList< CropOption>();

        意向意图=新的意图(com.android.camera.action.CROP);
        intent.setType(图像/ *);

        名单< ResolveInfo>表= getPackageManager()。queryIntentActivities(
                意图,0);

        INT大小=则为list.size();

        如果(大小== 0){
            Toast.makeText(这一点,找不到图像裁剪的应用程序,
                    Toast.LENGTH_SHORT).show();

            返回;
        } 其他 {

            intent.setData(mImageCaptureUri);
            intent.setClassName(com.android.camera
                    com.android.camera.CropImage);
            intent.putExtra(outputX,100);
            intent.putExtra(outputY,100);
            intent.putExtra(aspectX,1);
            intent.putExtra(aspectY,1);
            intent.putExtra(规模化,真正的);
            intent.putExtra(回归数据,真正的);
            // startActivityForResult(意向,CROP_FROM_CAMERA);

            如果(尺寸== 1){
                意图I =新的意向(意向);
                ResolveInfo解析度= list.get(0);

                i.setComponent(新的组件名(res.activityInfo.packageName,
                        res.activityInfo.name));

                startActivityForResult(ⅰ,CROP_FROM_CAMERA);
            } 其他 {
                对于(ResolveInfo RES:名单){
                    最后CropOption合作=新CropOption();

                    co.title = getPackageManager()。getApplicationLabel(
                            res.activityInfo.applicationInfo);
                    co.icon = getPackageManager()。getApplicationIcon(
                            res.activityInfo.applicationInfo);
                    co.appIntent =新的意图(意图);

                    co.appIntent
                            .setComponent(新的组件名(
                                    res.activityInfo.packageName,
                                    res.activityInfo.name));

                    cropOptions.add(共);
                }

                CropOptionAdapter适配器=新CropOptionAdapter(
                        getApplicationContext(),cropOptions);

                AlertDialog.Builder建设者=新AlertDialog.Builder(本);
                builder.setTitle(选择作物应用程序);
                builder.setAdapter(适配器,
                        新DialogInterface.OnClickListener(){
                            公共无效的onClick(DialogInterface对话,诠释项){
                                startActivityForResult(
                                        cropOptions.get(项目).appIntent,
                                        CROP_FROM_CAMERA);
                            }
                        });

                builder.setOnCancelListener(新DialogInterface.OnCancelListener(){
                    @覆盖
                    公共无效OnCancel的(DialogInterface对话){

                        如果(mImageCaptureUri!= NULL){
                            getContentResolver()。删除(mImageCaptureUri,空,
                                    空值);
                            mImageCaptureUri = NULL;
                        }
                    }
                });

                AlertDialog警报= builder.create();

                alert.show();
            }
        }
    }
}
 
中国旗袍分享 改良旗袍 少女旗袍 附旗袍纸样 工艺制作全套

I want to Crop the Capture/Selected Image and Upload it on to server.

What Problem I am Facing : After Cropping the Image i am not getting actual path for that Cropped Image. i have done my code below way. i am croping the image correctly also everything works fine here but imageview is not displaying original image instead of cropped image.

However when i have fetched bitmap with Bitmap photo = extras.getParcelable("data"); inside onActivityResult() i am getting Cropped image displayed in imageview.but not getting able to absolute path for that Cropped Image.

Can Anybody please guide me where i am lacking. i have tried with many SO links but not able to get exact solution for my issue.

Here is My Code :

public class MainActivity extends Activity {
    private Uri mImageCaptureUri;
    private ImageView mImageView;

    private static final int PICK_FROM_CAMERA = 1;
    private static final int CROP_FROM_CAMERA = 2;
    private static final int PICK_FROM_FILE = 3;

    private String selectedImagePath = "";
    boolean GallaryPhotoSelected = false;

    public static String Finalmedia = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        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) {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

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

                        startActivityForResult(intent, PICK_FROM_CAMERA);
                    } catch (ActivityNotFoundException e) {
                        e.printStackTrace();
                    }
                } else { // pick from file
                    Intent intent = new Intent();

                    intent.setType("image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);

                    startActivityForResult(Intent.createChooser(intent,
                            "Complete action using"), PICK_FROM_FILE);
                }
            }
        });

        final AlertDialog dialog = builder.create();

        Button button = (Button) findViewById(R.id.btn_crop);
        mImageView = (ImageView) findViewById(R.id.iv_photo);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.show();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK)
            return;

        switch (requestCode) {
        case PICK_FROM_CAMERA:
            doCrop();

            break;

        case PICK_FROM_FILE:
            mImageCaptureUri = data.getData();
            Log.i("TAG",
                    "After Crop mImageCaptureUri " + mImageCaptureUri.getPath());
            GallaryPhotoSelected = true;
            doCrop();

            break;

        case CROP_FROM_CAMERA:
            Bundle extras = data.getExtras();

            selectedImagePath = mImageCaptureUri.getPath();

            Log.i("TAG", "After Crop selectedImagePath " + selectedImagePath);

            if (GallaryPhotoSelected) {
                selectedImagePath = getRealPathFromURI(mImageCaptureUri);
                Log.i("TAG", "Absolute Path " + selectedImagePath);
                GallaryPhotoSelected = true;
            }

            Finalmedia = selectedImagePath;

            Log.i("TAG", "Finalmedia Path " + Finalmedia);

            if (extras != null) {
                Bitmap photo = extras.getParcelable("data");

                Bitmap bm = BitmapFactory.decodeFile(Finalmedia);

                mImageView.setImageBitmap(bm);
            }

            // File f = new File(mImageCaptureUri.getPath());
            //
            // if (f.exists()) f.delete();

            break;

        }
    }

    public static Bitmap decodeFile(String path) {
        int orientation;
        try {
            if (path == null) {
                return null;
            }
            // decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            // Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE = 70;
            int width_tmp = o.outWidth, height_tmp = o.outHeight;
            int scale = 2;
            // while (true) {
            // if (width_tmp / 2 < REQUIRED_SIZE
            // || height_tmp / 2 < REQUIRED_SIZE)
            // break;
            // width_tmp /= 2;
            // height_tmp /= 2;
            // scale++;
            // }
            // decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            Bitmap bm = BitmapFactory.decodeFile(path, o2);
            Bitmap bitmap = bm;

            ExifInterface exif = new ExifInterface(path);

            orientation = exif
                    .getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);

            Log.e("ExifInteface .........", "rotation =" + orientation);

            // exif.setAttribute(ExifInterface.ORIENTATION_ROTATE_90, 90);

            Log.e("orientation", "" + orientation);
            Matrix m = new Matrix();

            if ((orientation == ExifInterface.ORIENTATION_ROTATE_180)) {
                m.postRotate(180);
                // m.postScale((float) bm.getWidth(), (float) bm.getHeight());
                // if(m.preRotate(90)){
                Log.e("in orientation", "" + orientation);
                bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
                        bm.getHeight(), m, true);
                return bitmap;
            } else if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
                m.postRotate(90);
                Log.e("in orientation", "" + orientation);
                bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
                        bm.getHeight(), m, true);
                return bitmap;
            } else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
                m.postRotate(270);
                Log.e("in orientation", "" + orientation);
                bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
                        bm.getHeight(), m, true);
                return bitmap;
            }
            return bitmap;
        } catch (Exception e) {
            return null;
        }

    }

    public String getRealPathFromURI(Uri contentUri) {
        String[] proj = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(contentUri, proj, null, null, null);
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

    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, "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 = 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();
            }
        }
    }
}

解决方案

After spending hours on this issue i finally make it work by Below Way if some one is having this problem in future.

public class MainActivity extends Activity {
    private Uri mImageCaptureUri;
    private ImageView mImageView;

    private static final int PICK_FROM_CAMERA = 1;
    private static final int CROP_FROM_CAMERA = 2;
    private static final int PICK_FROM_FILE = 3;

    private String selectedImagePath = "";
    boolean GallaryPhotoSelected = false;

    public static String Finalmedia = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        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) {
                    String storageState = Environment.getExternalStorageState();

                    if (storageState.equals(Environment.MEDIA_MOUNTED)) {
                        Intent intent = new Intent(
                                MediaStore.ACTION_IMAGE_CAPTURE);
                        // intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT,
                        // mImageCaptureUri);
                        // if (hasImageCaptureBug()) {

                        String path = Environment.getExternalStorageDirectory()
                                .getName()
                                + File.separatorChar
                                + System.currentTimeMillis() + ".jpg";
                        File file = new File(path);
                        // mImageCaptureUri = Uri.fromFile(new File(
                        // Environment.getExternalStorageDirectory(),
                        // "tmp_avatar_"
                        // + String.valueOf(System
                        // .currentTimeMillis())
                        // + ".jpg"));
                        Log.i("TAG", "Final  path" + path);
                        try {
                            if (file.exists() == false) {
                                file.getParentFile().mkdirs();
                                file.createNewFile();
                            }

                        } catch (IOException e) {
                            Log.e("TAG", "Could not create file.", e);
                        }
                        mImageCaptureUri = Uri.fromFile(file);
                        intent.putExtra(
                                android.provider.MediaStore.EXTRA_OUTPUT,
                                mImageCaptureUri);
                        // } else {
                        // intent.putExtra(
                        // android.provider.MediaStore.EXTRA_OUTPUT,
                        // android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        // }

                        try {
                            // intent.putExtra("return-data", true);
                            startActivityForResult(intent, PICK_FROM_CAMERA);
                        } catch (ActivityNotFoundException e) {
                            e.printStackTrace();
                        }
                    } else {
                        new AlertDialog.Builder(MainActivity.this)
                                .setMessage(
                                        "External Storeage (SD Card) is required.nnCurrent state: "
                                                + storageState)
                                .setCancelable(true).create().show();
                    }

                } else { // pick from file
                    Intent intent = new Intent();

                    intent.setType("image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);

                    startActivityForResult(Intent.createChooser(intent,
                            "Complete action using"), PICK_FROM_FILE);
                }
            }
        });

        final AlertDialog dialog = builder.create();

        Button button = (Button) findViewById(R.id.btn_crop);
        mImageView = (ImageView) findViewById(R.id.iv_photo);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.show();
            }
        });
    }

    public boolean hasImageCaptureBug() {

        // list of known devices that have the bug
        ArrayList<String> devices = new ArrayList<String>();
        devices.add("android-devphone1/dream_devphone/dream");
        devices.add("generic/sdk/generic");
        devices.add("vodafone/vfpioneer/sapphire");
        devices.add("tmobile/kila/dream");
        devices.add("verizon/voles/sholes");
        devices.add("google_ion/google_ion/sapphire");

        return devices.contains(android.os.Build.BRAND + "/"
                + android.os.Build.PRODUCT + "/" + android.os.Build.DEVICE);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK)
            return;

        switch (requestCode) {
        case PICK_FROM_CAMERA:
            Log.i("TAG", "Inside PICK_FROM_CAMERA");
            // mImageCaptureUri = data.getData();
            // Bitmap bm1 = (Bitmap) data.getExtras().get("data");
            // mImageView.setImageBitmap(bm1);
            // Bundle extras1 = data.getExtras();
            // Bitmap bm1 = (Bitmap) extras1.get("data");
            // mImageView.setImageBitmap(bm1);

            /*
             * try { if (hasImageCaptureBug()) { Log.i("TAG", "Inside Bug");
             * selectedImagePath = String.valueOf(System .currentTimeMillis()) +
             * ".jpg"; File fi = new File(
             * Environment.getExternalStorageDirectory(), selectedImagePath);
             * try { mImageCaptureUri = Uri
             * .parse(android.provider.MediaStore.Images.Media
             * .insertImage(getContentResolver(), fi.getAbsolutePath(), null,
             * null)); if (!fi.delete()) { Log.i("logMarker",
             * "Failed to delete " + fi); } } catch (FileNotFoundException e) {
             * e.printStackTrace(); } } else { mImageCaptureUri =
             * data.getData(); } } catch (Exception e) { Log.i("TAG",
             * "Inside Bug"); selectedImagePath =
             * String.valueOf(System.currentTimeMillis()) + ".jpg"; File fi =
             * new File(Environment.getExternalStorageDirectory(),
             * selectedImagePath); try { mImageCaptureUri = Uri
             * .parse(android.provider.MediaStore.Images.Media
             * .insertImage(getContentResolver(), fi.getAbsolutePath(), null,
             * null)); if (!fi.delete()) { Log.i("logMarker",
             * "Failed to delete " + fi); } } catch (FileNotFoundException e1) {
             * e1.printStackTrace(); } }
             */

            String path = mImageCaptureUri.getPath();
            Log.i("TAG",
                    "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!After capture path "
                            + path);

            doCrop();

            break;

        case PICK_FROM_FILE:
            mImageCaptureUri = data.getData();
            Log.i("TAG",
                    "After Crop mImageCaptureUri " + mImageCaptureUri.getPath());
            GallaryPhotoSelected = true;
            doCrop();

            break;

        case CROP_FROM_CAMERA:
            Bundle extras = data.getExtras();

            selectedImagePath = mImageCaptureUri.getPath();

            Log.i("TAG", "After Crop selectedImagePath " + selectedImagePath);

            if (GallaryPhotoSelected) {
                selectedImagePath = getRealPathFromURI(mImageCaptureUri);
                Log.i("TAG", "Absolute Path " + selectedImagePath);
                GallaryPhotoSelected = true;
            }

            Finalmedia = selectedImagePath;

            if (extras != null) {
                // Bitmap photo = extras.getParcelable("data");
                Log.i("TAG", "Inside Extra " + selectedImagePath);
                Bitmap photo = (Bitmap) extras.get("data");

                selectedImagePath = String.valueOf(System.currentTimeMillis())
                        + ".jpg";

                Log.i("TAG", "new selectedImagePath before file "
                        + selectedImagePath);

                File file = new File(Environment.getExternalStorageDirectory(),
                        selectedImagePath);

                try {
                    file.createNewFile();
                    FileOutputStream fos = new FileOutputStream(file);
                    photo.compress(Bitmap.CompressFormat.PNG, 95, fos);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    Toast.makeText(this,
                            "Sorry, Camera Crashed-Please Report as Crash A.",
                            Toast.LENGTH_LONG).show();
                }

                selectedImagePath = Environment.getExternalStorageDirectory()
                        + "/" + selectedImagePath;
                Log.i("TAG", "After File Created  " + selectedImagePath);

                Bitmap bm = decodeFile(selectedImagePath);
                mImageView.setImageBitmap(bm);
            }

            /*
             * File f = new File(mImageCaptureUri.getPath());
             * 
             * if (f.exists()) f.delete();
             */

            break;

        }
    }

    public static Bitmap decodeFile(String path) {
        int orientation;
        try {
            if (path == null) {
                return null;
            }
            // decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            // Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE = 70;
            int width_tmp = o.outWidth, height_tmp = o.outHeight;
            int scale = 1;
            // while (true) {
            // if (width_tmp / 2 < REQUIRED_SIZE
            // || height_tmp / 2 < REQUIRED_SIZE)
            // break;
            // width_tmp /= 2;
            // height_tmp /= 2;
            // scale++;
            // }
            // decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            Bitmap bm = BitmapFactory.decodeFile(path, o2);
            Bitmap bitmap = bm;

            ExifInterface exif = new ExifInterface(path);

            orientation = exif
                    .getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);

            Log.e("ExifInteface .........", "rotation =" + orientation);

            // exif.setAttribute(ExifInterface.ORIENTATION_ROTATE_90, 90);

            Log.e("orientation", "" + orientation);
            Matrix m = new Matrix();

            if ((orientation == ExifInterface.ORIENTATION_ROTATE_180)) {
                m.postRotate(180);
                // m.postScale((float) bm.getWidth(), (float) bm.getHeight());
                // if(m.preRotate(90)){
                Log.e("in orientation", "" + orientation);
                bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
                        bm.getHeight(), m, true);
                return bitmap;
            } else if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
                m.postRotate(90);
                Log.e("in orientation", "" + orientation);
                bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
                        bm.getHeight(), m, true);
                return bitmap;
            } else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
                m.postRotate(270);
                Log.e("in orientation", "" + orientation);
                bitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
                        bm.getHeight(), m, true);
                return bitmap;
            }
            return bitmap;
        } catch (Exception e) {
            return null;
        }

    }

    public String getRealPathFromURI(Uri contentUri) {
        String[] proj = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(contentUri, proj, null, null, null);
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

    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, "Can not find image crop app",
                    Toast.LENGTH_SHORT).show();

            return;
        } else {

            intent.setData(mImageCaptureUri);
            intent.setClassName("com.android.camera",
                    "com.android.camera.CropImage");
            intent.putExtra("outputX", 100);
            intent.putExtra("outputY", 100);
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
            intent.putExtra("scale", true);
            intent.putExtra("return-data", true);
            // startActivityForResult(intent, CROP_FROM_CAMERA);

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

阅读全文

相关推荐

最新文章