获取sdcard下所有图片的路径

第一种:

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.os.Environment;
import android.util.Log;

public class SDcardImageService {
 /**
  * 获得SDcard下的所有的图片路径
  *
  * @return 返回image的path
  */
 public static List getImagesFromSD() {
  imagePaths = new ArrayList();
  if (Environment.getExternalStorageState().equals(
    Environment.MEDIA_MOUNTED)
    || Environment.getExternalStorageState().equals(
      Environment.MEDIA_MOUNTED_READ_ONLY)) {
   
   File path = Environment.getExternalStorageDirectory();

   File file = new File(path.getPath());

   File[] files = file.listFiles();

   getFileName(files);
  }
  return imagePaths;
 }

 private static String[] imageFormatSet = new String[] { "jpg", "png", "gif" };
 private static List imagePaths;

 private static boolean isImageFile(String path) {

  for (String format : imageFormatSet) {
   if (path.contains(format)) {
    return true;
   }
  }
  return false;
 }

 private static void getFileName(File[] files) {

  for (File currentFile : files) {

   // 判断是一个文件夹还是一个文件

   if (currentFile.isDirectory()) {
    File[] listFiles = currentFile.listFiles();
    if(currentFile.listFiles() != null && currentFile.listFiles().length > 0){
     getFileName(currentFile.listFiles());
    }

   } else {

    // 取得文件名

    String fileName = currentFile.getName();

    if (isImageFile(fileName)){

     // 保存文件名
     System.out.println(fileName);
     imagePaths.add(fileName);
    }
   }
  }
 }
}

 

第二种直接数据库查询

Cursor cursor = managedQuery(
                      MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null,
                      null, MediaStore.Images.Media.DEFAULT_SORT_ORDER);
              cursor.moveToFirst();
 
              while (!cursor.isAfterLast()) {
                  String data = cursor.getString(cursor
                          .getColumnIndex(MediaStore.MediaColumns.DATA));

                  System.out.println(data);
                  cursor.moveToNext();
              }

亲测可用

你可能感兴趣的:(获取图片)