0

我想将图库中的位图复制到SD卡上的路径。从图库中读取位图并将其写入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")); 
    } 
} 

任何帮助?

回答

0

最后我得到了原因,这是因为文件路径问题。

这是我用什么:

Uri uri = ....; 
path = uri.toString(); 

导致的前缀文件:///加入到像路径字符串:

file:///storage/...png 

希望可以帮助一些人。