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 

希望可以幫助一些人。