我想将图库中的位图复制到sd卡上的路径。
此功能适用于从相机拍摄的照片:
public void saveBitmap(Bitmap bitMap, Uri avatarUri) throws Exception{
File file = new File(avatarUri.toString());
// if (file.exists ()) file.delete ();
try {
OutputStream fOut = new FileOutputStream(file);
if (bitMap.compress(Bitmap.CompressFormat.PNG, 100, fOut)) {
fOut.flush();
fOut.close();
} else {
Log.d("123", "compress file");
}
} catch (Exception e) {
Log.d("123", "File not found file");
}
}
但是当我使用以下方法从图库中选择图像时:
void getImageFromGallery(Intent data) throws FileNotFoundException {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = context.getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
Bitmap bitmap = BitmapFactory.decodeFile(picturePath);
avatarBitmap = bitmap;
}
并使用
saveBitmap()
方法保存选择的图像,它将捕获File not found
异常。此方法生成一个文件夹,并返回
saveBitmap()
方法的URI。 public Uri generateAvatarImageUri(String patientName) {
Date date = new Date(0);
SimpleDateFormat sdf = new SimpleDateFormat ("yyyyMMddHHmmss");
String filename = sdf.format(date) + patientName;
return Uri.fromFile(new File(getExternalStorageDirectory(), avatarFolderPath+filename+".jpg"));
}
}
有什么帮助吗?
最佳答案
最后我明白了原因,这是因为文件路径问题。
这是我用的:
Uri uri = ....;
path = uri.toString();
导致前缀file:///被添加到路径字符串中,如下所示:
file:///storage/...png
希望可以帮助其他人。