解決Android拍照保存在系統相冊不顯示的問題


可能大家都知道我們保存相冊到Android手機的時候,然后去打開系統圖庫找不到我們想要的那張圖片,那是因為我們插入的圖片還沒有更新的緣故,先講解下插入系統圖庫的方法吧,很簡單,一句代碼就能實現

 

[java]  view plain  copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. MediaStore.Images.Media.insertImage(getContentResolver(), mBitmap, "", "");  

通過上面的那句代碼就能插入到系統圖庫,這時候有一個問題,就是我們不能指定插入照片的名字,而是系統給了我們一個當前時間的毫秒數為名字,有一個問題郁悶了很久,我還是先把insertImage的源碼貼出來吧

 

 

[java]  view plain  copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. /** 
  2.             * Insert an image and create a thumbnail for it. 
  3.             * 
  4.             * @param cr The content resolver to use 
  5.             * @param source The stream to use for the image 
  6.             * @param title The name of the image 
  7.             * @param description The description of the image 
  8.             * @return The URL to the newly created image, or <code>null</code> if the image failed to be stored 
  9.             *              for any reason. 
  10.             */  
  11.            public static final String insertImage(ContentResolver cr, Bitmap source,  
  12.                                                   String title, String description) {  
  13.                ContentValues values = new ContentValues();  
  14.                values.put(Images.Media.TITLE, title);  
  15.                values.put(Images.Media.DESCRIPTION, description);  
  16.                values.put(Images.Media.MIME_TYPE, "image/jpeg");  
  17.   
  18.                Uri url = null;  
  19.                String stringUrl = null;    /* value to be returned */  
  20.   
  21.                try {  
  22.                    url = cr.insert(EXTERNAL_CONTENT_URI, values);  
  23.   
  24.                    if (source != null) {  
  25.                        OutputStream imageOut = cr.openOutputStream(url);  
  26.                        try {  
  27.                            source.compress(Bitmap.CompressFormat.JPEG, 50, imageOut);  
  28.                        } finally {  
  29.                            imageOut.close();  
  30.                        }  
  31.   
  32.                        long id = ContentUris.parseId(url);  
  33.                        // Wait until MINI_KIND thumbnail is generated.  
  34.                        Bitmap miniThumb = Images.Thumbnails.getThumbnail(cr, id,  
  35.                                Images.Thumbnails.MINI_KIND, null);  
  36.                        // This is for backward compatibility.  
  37.                        Bitmap microThumb = StoreThumbnail(cr, miniThumb, id, 50F, 50F,  
  38.                                Images.Thumbnails.MICRO_KIND);  
  39.                    } else {  
  40.                        Log.e(TAG, "Failed to create thumbnail, removing original");  
  41.                        cr.delete(url, null, null);  
  42.                        url = null;  
  43.                    }  
  44.                } catch (Exception e) {  
  45.                    Log.e(TAG, "Failed to insert image", e);  
  46.                    if (url != null) {  
  47.                        cr.delete(url, null, null);  
  48.                        url = null;  
  49.                    }  
  50.                }  
  51.   
  52.                if (url != null) {  
  53.                    stringUrl = url.toString();  
  54.                }  
  55.   
  56.                return stringUrl;  
  57.            }  

上面方法里面有一個title,我剛以為是可以設置圖片的名字,設置一下,原來不是,郁悶,哪位高手知道title這個字段是干嘛的,告訴下小弟,不勝感激!

 

當然Android還提供了一個插入系統相冊的方法,可以指定保存圖片的名字,我把源碼貼出來吧

 

[java]  view plain  copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. /** 
  2.           * Insert an image and create a thumbnail for it. 
  3.           * 
  4.           * @param cr The content resolver to use 
  5.           * @param imagePath The path to the image to insert 
  6.           * @param name The name of the image 
  7.           * @param description The description of the image 
  8.           * @return The URL to the newly created image 
  9.           * @throws FileNotFoundException 
  10.           */  
  11.          public static final String insertImage(ContentResolver cr, String imagePath,  
  12.                  String name, String description) throws FileNotFoundException {  
  13.              // Check if file exists with a FileInputStream  
  14.              FileInputStream stream = new FileInputStream(imagePath);  
  15.              try {  
  16.                  Bitmap bm = BitmapFactory.decodeFile(imagePath);  
  17.                  String ret = insertImage(cr, bm, name, description);  
  18.                  bm.recycle();  
  19.                  return ret;  
  20.              } finally {  
  21.                  try {  
  22.                      stream.close();  
  23.                  } catch (IOException e) {  
  24.                  }  
  25.              }  
  26.          }  

啊啊,貼完源碼我才發現,這個方法調用了第一個方法,這個name就是上面方法的title,暈死,這下更加郁悶了,反正我設置title無效果,求高手為小弟解答,先不管了,我們繼續往下說

 

上面那段代碼插入到系統相冊之后還需要發條廣播

 

[java]  view plain  copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+ Environment.getExternalStorageDirectory())));    

上面那條廣播是掃描整個sd卡的廣播,如果你sd卡里面東西很多會掃描很久,在掃描當中我們是不能訪問sd卡,所以這樣子用戶體現很不好,用過微信的朋友都知道,微信保存圖片到系統相冊並沒有掃描整個SD卡,所以我們用到下面的方法

 

 

[java]  view plain  copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);     
  2.  Uri uri = Uri.fromFile(new File("/sdcard/image.jpg"));     
  3.  intent.setData(uri);     
  4.  mContext.sendBroadcast(intent);    

或者用MediaScannerConnection

 

 

[java]  view plain  copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. final MediaScannerConnection msc = new MediaScannerConnection(mContext, new MediaScannerConnectionClient() {     
  2.   public void onMediaScannerConnected() {     
  3.    msc.scanFile("/sdcard/image.jpg", "image/jpeg");     
  4.   }     
  5.   public void onScanCompleted(String path, Uri uri) {     
  6.    Log.v(TAG, "scan completed");     
  7.    msc.disconnect();     
  8.   }     
  9.  });     

也行你會問我,怎么獲取到我們剛剛插入的圖片的路徑?呵呵,這個自有方法獲取,insertImage(ContentResolver cr, Bitmap source,String title, String description),這個方法給我們返回的就是插入圖片的Uri,我們根據這個Uri就能獲取到圖片的絕對路徑

 

 

[java]  view plain  copy
 
 在CODE上查看代碼片派生到我的代碼片
  1. private  String getFilePathByContentResolver(Context context, Uri uri) {  
  2.         if (null == uri) {  
  3.             return null;  
  4.         }  
  5.         Cursor c = context.getContentResolver().query(uri, null, null, null, null);  
  6.         String filePath  = null;  
  7.         if (null == c) {  
  8.             throw new IllegalArgumentException(  
  9.                     "Query on " + uri + " returns null result.");  
  10.         }  
  11.         try {  
  12.             if ((c.getCount() != 1) || !c.moveToFirst()) {  
  13.             } else {  
  14.                 filePath = c.getString(  
  15.                         c.getColumnIndexOrThrow(MediaColumns.DATA));  
  16.             }  
  17.         } finally {  
  18.             c.close();  
  19.         }  
  20.         return filePath;  
  21.     }  

根據上面的那個方法獲取到的就是圖片的絕對路徑,這樣子我們就不用發送掃描整個SD卡的廣播了,呵呵,寫到這里就算是寫完了,寫的很亂,希望大家將就的看下,希望對你有幫助!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM