1

我正在创建一个安卓应用程序。它会拍一张照片,然后让你裁剪它,然后显示它。问题是它只保存拍摄的图像而不是裁剪的图像。基本上我需要它来保存裁剪的图像。裁剪后如何保存文件?

代码:

private void performCrop(){
    //take care of exceptions
    try {
        //call the standard crop action intent (the user device may not support it)
        Intent cropIntent = new Intent("com.android.camera.action.CROP"); 
        //indicate image type and Uri
        cropIntent.setDataAndType(picUri, "image/*");
        //set crop properties
        cropIntent.putExtra("crop", "true");
        //indicate aspect of desired crop
        cropIntent.putExtra("aspectX", 1);
        cropIntent.putExtra("aspectY", 1.5);
        //indicate output X and Y
        cropIntent.putExtra("outputX", 256);
        cropIntent.putExtra("outputY", 256);
        //retrieve data on return
        cropIntent.putExtra("return", true);
        //start the activity - we handle returning in onActivityResult
        startActivityForResult(cropIntent, PIC_CROP);  

    }

    //respond to users whose devices do not support the crop action
    catch(ActivityNotFoundException anfe){
        //display an error message 
        String errorMessage = "Your device does not support cropping";
        Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
        toast.show();
    }
}
4

1 回答 1

3

只需添加如下内容:

    try{    
        File file = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES 
            ), fileName+".png"); //save to your pictures folder
     outputFileURI = Uri.fromFile(file);

     cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileURI);
     startActivityForResult(cropIntent, PIC_CROP); 
    } catch (IOException ioe){ 
        // handle your exception
     }

请记住在保存后刷新图库,以便它立即在图库中可用。因此,也许在您的 onActivityResult 方法中使用此代码?

sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse
                    ("file://" + Environment.getExternalStorageDirectory())));

编辑:找到了一种更好的刷新图库的方法,因为如果您只是刷新一张图像,sendBroadcast 可能效率低下。使用 MediaScanner 像这样扫描文件

Intent intent =   new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); 
                intent.setData(outputFileURI); // Add the path to the file
                sendBroadcast(intent); 

这只会扫描新文件并刷新它而不是整个图库。

于 2013-07-31T14:08:22.670 回答