如何在裁剪后获取保存图像的文件名和路径

时间:2015-09-14 07:13:42

标签: android android-file

我有一个带有图像裁剪选项的应用。裁剪实际图像后,裁剪后的图像将保存在图库中。我的问题是如何检索保存在图库中的裁剪图像的文件名和路径。

我的代码是,

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

            doCrop();

            break;          

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

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

                mImageView.setImageBitmap(photo);
            }

            File f = new File(mImageCaptureUri.getPath());            

            if (f.exists()) f.delete();

            break;

    }
}

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

我已经尝试了很多,但没有检索文件名和路径。有没有解决方案。

1 个答案:

答案 0 :(得分:2)

您正在使用startActivityForResult(),但是您是否覆盖了onActivityResult()?在您的情况下,您需要执行以下操作:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
   if (requestCode == PICK_FROM_FILE && resultCode == RESULT_OK)
   { 
      Uri pictureUri = data.getData();
   }
}

此代码获取图片的Uri。然后你可以使用这个Uri来获取路径,使用如下方法:

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

修改

在裁剪了Bitmap并准备好之后,您可以使用以下内容进行保存:

private Uri saveOutput(Bitmap croppedImage)    
{
    Uri saveUri = null;
    // Saves the image in cache, you may want to modify this to save it to Gallery
    File file = new File(getCacheDir(), "cropped");
    OutputStream outputStream = null;
    try
    {
        file.getParentFile().mkdirs();
        saveUri = Uri.fromFile(file);
        outputStream = getContentResolver().openOutputStream(saveUri);
        if (outputStream != null)
        {
            croppedImage.compress(Bitmap.CompressFormat.JPEG, 90, outputStream);
        }
    } catch (IOException e)
    {
        // log the error
    }

    return saveUri;
}

获得Uri后,您可以使用上述相同的方法获得裁剪图像的路径。