Android 读取本地图片

211

创建一个工具类 :FileUtil

package com.example.testUtil;

import java.io.File;
//从本地读取图片
public class FileUtil {
    public static String[] getImageNames(String folderPath) {
        File file01 = new File(folderPath);

        String[] files01 = file01.list();

        int imageFileNums = 0;
        for (int i = 0; i < files01.length; i++) {
            File file02 = new File(folderPath + "/" + files01[i]);

            if (!file02.isDirectory()) {

                if (isImageFile(file02.getName())) {

                    imageFileNums++;
                }
            }
        }

        String[] files02 = new String[imageFileNums];

        int j = 0;
        for (int i = 0; i < files01.length; i++) {
            File file02 = new File(folderPath + "/" + files01[i]);

            if (!file02.isDirectory()) {

                if (isImageFile(file02.getName())) {
                    files02[j] = file02.getName();
                    j++;
                }
            }
        }
        return files02;
    }

    private static boolean isImageFile(String fileName) {
        String fileEnd = fileName.substring(fileName.lastIndexOf(".") + 1,
                fileName.length());
        if (fileEnd.equalsIgnoreCase("jpg")) {
            return true;
        } else if (fileEnd.equalsIgnoreCase("png")) {
            return true;
        } else if (fileEnd.equalsIgnoreCase("bmp")) {
            return true;
        } else {
            return false;
        }
    }

}

然后在我们的主方法中去调用:

String[] titles = FileUtil.getImageNames("/mnt/sdcard/lzlpicture/87-32101010/"); //图片名称
String[] imagePaths = new String[titles.length];   // 存储图片的数组

for (int i = 0; i < titles.length; i++) {
    imagePaths[i] = "/mnt/sdcard/lzlpicture/87-32101010/" + titles[i];
}
mImage.setImageBitmap(BitmapFactory.decodeFile(imagePaths[1]));  //图片就能显示到Imageview上了


千万不能忘记添加我们的权限:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />