1 /** 2 * 保存圖片到相冊 3 */ 4 public void saveImageToGallery(Bitmap mBitmap) { 5 if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { 6 7 ToastUtils.showToast(CodeActivity.this, "sdcard未使用"); 8 return; 9 } 10 // 首先保存圖片 11 File appDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsoluteFile(); 12 if (!appDir.exists()) { 13 appDir.mkdir(); 14 } 15 String fileName = System.currentTimeMillis() + ".jpg"; 16 File file = new File(appDir, fileName); 17 try { 18 FileOutputStream fos = new FileOutputStream(file); 19 mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos); 20 fos.flush(); 21 fos.close(); 22 } catch (FileNotFoundException e) { 23 e.printStackTrace(); 24 return; 25 } catch (IOException e) { 26 e.printStackTrace(); 27 return; 28 } 29 30 // 其次把文件插入到系統圖庫 31 try { 32 MediaStore.Images.Media.insertImage(getApplication().getContentResolver(), file.getAbsolutePath(), fileName, null); 33 } catch (FileNotFoundException e) { 34 e.printStackTrace(); 35 } // 最后通知圖庫更新 36 37 getApplication().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + ""))); 38 39 40 }