android - 裁剪后如何保存文件?

标签 android image crop

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

代码:

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

最佳答案

只需添加如下内容:

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

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

关于android - 裁剪后如何保存文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13326825/

相关文章:

android - 在 Objective C、.net 和 Android 中生成相同的加密字符串 AES/CBC/PKCS7Padding

Android:监控应用程序的网络流量,使用类似于 F12->Network on Web 的工具

python - 使用 PIL 裁剪 jpeg 图像是无损的吗?

xcode - 如何在 Xcode 中制作可调整大小的裁剪矩形来裁剪图像?

android - 在android中显示图像,文件名中有空格来自在线

android - 对话框上的后退按钮正在取消对话框,即使我有一个监听器

javascript - 在固定大小的 div 中显示图像

android - 如何在Android中逐像素显示位图?

html - 链接和图像居中

android - 无法使用 google photos 上传图片