裁剪图像而不创建新文件

时间:2012-08-31 20:22:52

标签: android android-intent bitmap crop

我有这段代码从图库中获取图像,然后将其传递给意图进行裁剪。一切正常,但要么在画廊中创建新的裁剪图像,要么用裁剪的图像替换旧图像,但我想要做的是将新裁剪的图像保留在我的程序临时内存中,直到用户再次更改为止。

这是我的代码:

Uri selectedImage = imageReturnedIntent.getData();

final Intent intent = new Intent("com.android.camera.action.CROP");
                intent.setData(selectedImage);
                intent.putExtra("outputX", width);
                intent.putExtra("outputY", height);
                intent.putExtra("aspectX", width);
                intent.putExtra("aspectY", height);
                intent.putExtra("scale", true);
                intent.putExtra("noFaceDetection", true);
                intent.putExtra("output", selectedImage); // with this enabled it replaces the original image and without it creates new one in gallery.
                startActivityForResult(intent, 23);

1 个答案:

答案 0 :(得分:5)

您应该创建一个临时文件,然后删除:

    (...)
    File tempFile = File.createTempFile("crop", "png", Environment
                                            .getExternalStorageDirectory());
    Uri tempUri = Uri.fromFile(tempFile);
    intent.putExtra("output", tempUri);
    intent.putExtra("outputFormat", "PNG");
    (...)

    // then, when the intent returns

    // read cropped image from tempUri
    (...)
    // finally delete the temp file
    tempFile.delete();