上面的解决方案对我有用,但有细微的变化:
相机点击的图片由 ACTION_IMAGE_CAPTURE Intent 保存。而对于我们自己的应用程序从图库中挑选图像,我们需要保存来自 ACTION_PICK 意图的图像。在这种情况下保存基本上是在 ImageView 中显示图像后将图像从图库复制到您自己的应用程序文件夹。
首先你需要有目标文件:所以调用以下方法来获取你的应用程序的目录,它位于Android>data>YOUR APP FOLDER>Files>Pictures:
private File mPhotoFile;
mPhotoFile=PhotoLab.get(getActivity()).getPhotoFile(mPhoto);
这里是 getPhotoFile() 函数
public File getPhotoFile(Photo photo){
File externalFilesDir=mContext.getExternalFilesDir(Environment.DIRECTORY_PICTURES);//getExternalStorageDirectory().toString());
if(externalFilesDir==null){
return null;
}
return new File(externalFilesDir, photo.getPhotoFilename());
}
现在您有了要保存由 Image Intent 选取的图像的文件。现在调用 ACTION_PICK 意图。
private static final int PICK_IMAGE_REQUEST=2;
Intent pickIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI); //Trying intent to pick image from gallery
pickIntent.setType("image/*");
Uri uriImagePath = Uri.fromFile(mPhotoFile);
pickIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriImagePath);
startActivityForResult(pickIntent, PICK_IMAGE_REQUEST);
在onActivityResult中收到结果后,下面是我的代码:
if(requestCode==PICK_IMAGE_REQUEST){
Picasso.with(getActivity()).load(data.getData()).fit().into(mPhotoView);
File file=getBitmapFile(data);
try {
copyFile(file, mPhotoFile);
}catch(IOException e){
Toast.makeText(getActivity(),"Cannot use Gallery, Try Camera!",Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
获取数据后,我将其传递给 next 方法,以通过 Intent.ACTION_PICK 找到所取图像的绝对路径。以下是方法定义:
public File getBitmapFile(Intent data){
Uri selectedImage=data.getData();
Cursor cursor=getContext().getContentResolver().query(selectedImage, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
cursor.moveToFirst();
int idx=cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
String selectedImagePath=cursor.getString(idx);
cursor.close();
return new File(selectedImagePath);
}
获取到所选取图片的绝对路径后。我调用了 copyFile() 函数。如下。请记住,我已经生成了新的文件路径。
public File getBitmapFile(Intent data){
Uri selectedImage=data.getData();
Cursor cursor=getContext().getContentResolver().query(selectedImage, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
cursor.moveToFirst();
int idx=cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
String selectedImagePath=cursor.getString(idx);
cursor.close();
return new File(selectedImagePath);
}
我的目的地是 mPhotoFile。我们首先生成的。
如果您想从图库中选择图像并将其存储以在每次打开时进一步显示在应用程序的 imageView 中,则整个代码将起作用。