2015-06-19 61 views
1

我使用下面的代碼將位圖圖像(從佈局捕獲)保存到android默認圖片目錄中。看起來保存的圖像已損壞,因爲Gallery無法打開它。將位圖保存到android默認圖片目錄

當我將位圖保存在另一個位置時,畫廊可以打開它。但是當我將它保存到android默認目錄時它不會打開。

public void saveToGallery() { 
     String path = Environment.getExternalStorageDirectory().toString() 
       + "/Pictures/Keshavarzi/" + "screenshot-" + System.currentTimeMillis() + ".png"; 

     ViewGroup v = (ViewGroup) findViewById(R.id.lyt_main_report_activity); 
     v.setDrawingCacheEnabled(true); 
     v.setDrawingCacheEnabled(true); 
     v.buildDrawingCache(); 
     Bitmap bitmap = Bitmap.createBitmap(v.getDrawingCache()); 
     v.setDrawingCacheEnabled(false); 



     OutputStream out = null; 
     File imageFile = new File(path); 

     try { 
      out = new FileOutputStream(imageFile); 
      bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out); 
      out.flush(); 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       if (out != null) { 
        out.close(); 
       } 

      } catch (Exception exc) { 
      } 

     } 


     ContentValues values = new ContentValues(); 
     values.put(MediaStore.Images.Media.TITLE, "Title"); 
     values.put(MediaStore.Images.Media.DESCRIPTION, "Description"); 
     values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis()); 
     values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg"); 
     values.put(MediaStore.MediaColumns.DATA, path); 

     getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); 


     MHToast.showToast(getString(R.string.saved_in_gallery), Toast.LENGTH_LONG); 
    } 
+0

你必須檢查它是否存在或不是文件路徑。如果不存在,則創建它。 – Pankaj

回答

1

試試這個,請檢查您的保存目錄的存在,或先創建目錄,然後保存位圖,

String path = Environment.getExternalStorageDirectory().toString() 
      + "/Pictures/Keshavarzi/" + "screenshot-" + 

System.currentTimeMillis() + ".png"; 
File imageFile = new File(path); 
if(!imageFile.getParentFile().exists()){ 
     imageFile.getParentFile().mkDirs(); 
} 
+0

您的回答是正確的,問題是我沒有檢查路徑是否存在。但getParent()返回String。我爲父目錄創建一個新文件並檢查它。請編輯你的答案,以便我可以接受它 –

+0

對不起我的錯誤:)。答案已更新。 – WonderSoftwares