最近有些用戶反映保存圖片以後在系統圖庫找不到保存的圖片,遂決定完全查看並解決下。數據庫
Adnroid中保存圖片的方法可能有以下兩種:app
第一種是本身寫方法,以下代碼:code
public static File saveImage(Bitmap bmp) { File appDir = new File(Environment.getExternalStorageDirectory(), "Boohee"); if (!appDir.exists()) { appDir.mkdir(); } String fileName = System.currentTimeMillis() + ".jpg"; File file = new File(appDir, fileName); try { FileOutputStream fos = new FileOutputStream(file); bmp.compress(CompressFormat.JPEG, 100, fos); fos.flush(); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
以上代碼即是將Bitmap保存圖片到指定的路徑/sdcard/Boohee/下,文件名以當前系統時間命名,可是這種方法保存的圖片沒有加入到系統圖庫中orm
第二種是調用系統提供的插入圖庫的方法:對象
MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "title", "description");
調用以上系統自帶的方法會把bitmap對象保存到系統圖庫中,可是這種方法沒法指定保存的路徑和名稱,上述方法的title、description參數只是插入數據庫中的字段,真實的圖片名稱系統會自動分配。圖片
看似上述第二種方法就是咱們要用到的方法,可是惋惜的調用上述第二種插入圖庫的方法圖片並無馬上顯示在圖庫中,而咱們須要馬上更新系統圖庫以便讓用戶能夠馬上查看到這張圖片。ip
更新系統圖庫的方法get
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
上面那條廣播是掃描整個sd卡的廣播,若是你sd卡里面東西不少會掃描好久,在掃描當中咱們是不能訪問sd卡,因此這樣子用戶體現很很差,因此下面咱們還有以下的方法:it
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File("/sdcard/Boohee/image.jpg"))););
或者還有以下方法:io
final MediaScannerConnection msc = new MediaScannerConnection(mContext, new MediaScannerConnectionClient() { public void onMediaScannerConnected() { msc.scanFile("/sdcard/Boohee/image.jpg", "image/jpeg"); } public void onScanCompleted(String path, Uri uri) { Log.v(TAG, "scan completed"); msc.disconnect(); } });
上面代碼的圖片路徑無論是經過本身寫方法仍是系統插入圖庫的方法均可以很容易的獲取到。
終極完美解決方案
那麼到這裏可能有人又會問了,若是我想把圖片保存到指定的文件夾,同時又須要圖片出如今圖庫裏呢?答案是能夠的,sdk還提供了這樣一個方法:
MediaStore.Images.Media.insertImage(getContentResolver(), "image path", "title", "description");
上述方法的第二個參數是image path,這樣的話就有思路了,首先本身寫方法把圖片指定到指定的文件夾,而後調用上述方法把剛保存的圖片路徑傳入進去,最後通知圖庫更新。
因此寫了一個方法,完整的代碼以下:
public static void saveImageToGallery(Context context, Bitmap bmp) { // 首先保存圖片 File appDir = new File(Environment.getExternalStorageDirectory(), "Boohee"); if (!appDir.exists()) { appDir.mkdir(); } String fileName = System.currentTimeMillis() + ".jpg"; File file = new File(appDir, fileName); try { FileOutputStream fos = new FileOutputStream(file); bmp.compress(CompressFormat.JPEG, 100, fos); fos.flush(); fos.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // 其次把文件插入到系統圖庫 try { MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null); } catch (FileNotFoundException e) { e.printStackTrace(); } // 最後通知圖庫更新 context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path))); }