//功能:将SD卡中的绝对路径中的图片显示完出来,缩略形式显示 //主布局文件 <GridView android:id="@+id/gridview" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#000" android:columnWidth="150dp" android:numColumns="auto_fit" /> <TextView android:id="@+id/empty" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/gridview" android:text="没有更多数据" /> //主程序代码 public class MainActivity extends Activity { private GridView gridview; private List<String> ImageList = new ArrayList<String>();// 用来存放图片的名称 private TextView empty; private String[] imageType = { "jpg", "png" };// 用来判断路径中的文件是不是这种格式的图片,是就加入到list中 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); this.gridview = (GridView) this.findViewById(R.id.gridview); this.empty = (TextView) this.findViewById(R.id.empty); gridview.setEmptyView(empty); String path = FileUtils.getSDCRRDDIR();// SD卡根路径 getPathFiles(path);// 定义一个方法来查找图片文件 myAdapter adapter = new myAdapter(ImageList); gridview.setAdapter(adapter); } public void getPathFiles(String path) { File file = new File(path); File[] imageFile = file.listFiles(); if (imageFile != null && imageFile.length > 0) { for (File files : imageFile) { if (files.isDirectory()) {// 是目录递归 getPathFiles(files.getAbsolutePath()); } else {// 是文件判断是不是图片 if (isImageFile(files.getPath())) { ImageList.add(files.getPath()); } } } } } // 判断图片是否为本身数组中定义的格式 public boolean isImageFile(String path) { for (String format : imageType) { if (path.endsWith(format)) { return true; } } return false; } class myAdapter extends BaseAdapter { private List<String> list; public myAdapter(List<String> imageList) { this.list = imageList; } @Override public int getCount() { return this.list.size(); } @Override public Object getItem(int position) { return this.list.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { // 这里没有建一个布局,因此直接用代码new一个ImageView ImageView imageView = null; if (convertView == null) { imageView = new ImageView(MainActivity.this); // 设置图片的最大宽度高度,和背景,内边距 imageView.setMaxWidth(90); imageView.setMaxHeight(90); imageView.setBackgroundResource(R.drawable.image_border); imageView.setPadding(2, 2, 2, 2); } else { imageView = (ImageView) convertView; } // 设置UI显示的图片,二次裁剪,缩略图 Bitmap bitmap = FileUtils.createThumbnail(list.get(position), 90, 90); imageView.setImageBitmap(bitmap); // 点击每一个缩略图的时候跳到大图显示,看原图,这个就要调用自带的看图工具 // 图片的监听事件 imageView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setAction(intent.ACTION_VIEW); intent.setDataAndType( Uri.fromFile(new File(list.get(position))), "image/*"); startActivity(intent); } }); return imageView; } } } //工具类 public class FileUtils { /** * 操做SDcard卡的文件工具类 */ // 获取当前的SD卡的根路径// 定义一个缓存目录 private static final String SDCACHE_DIR = Environment .getExternalStorageDirectory() + "/myimages"; private static final int COMP_JPG = 0;// 图片类型常量 private static final int COMP_PNG = 1; private static final String TAG = "MainActivity"; /** * 判断SD卡是否挂载 * * @return */ public static boolean isSDMount() { String state = Environment.getExternalStorageState(); return state.equals(Environment.MEDIA_MOUNTED); } /** * 获取SD卡文件根路径的绝对路径 获取sdcard绝对物理路径 * * @return */ public static String getSDCRRDDIR() { if (isSDMount()) { return Environment.getExternalStorageDirectory().getAbsolutePath(); } else { return null; } } /** * 获取SD卡的所有空间大小,返回MB字节 * * @return */ public static long getSDCardSize() { // 借助StatFs类获取SD卡空间大小 if (isSDMount()) { StatFs stf = new StatFs(getSDCRRDDIR()); // long size=stf.getBlockSize();过期 long size = stf.getBlockSizeLong(); // long count=stf.stf.getBlockCount(); long count = stf.getBlockCountLong(); return size * count / 1024 / 1024; } return 0; } /** * 获取sdcard的剩余的可用空间的大小。返回MB字节 * * @return */ public static long getSDCardFreeSize() { if (isSDMount()) { StatFs stf = new StatFs(getSDCRRDDIR()); long size = stf.getBlockSizeLong(); long count = stf.getAvailableBlocksLong(); return size * count / 1024 / 1024; } return 0; } /** * 保存图片方法一 * * @param url * @param data */ public static void saveImage(String url, byte[] data) { // 一、判断是否有SD卡 if (!isSDMount()) { return; } // 2.判断是否有缓存的文件夹 File file = new File(SDCACHE_DIR); if (!file.exists()) { file.mkdirs();// 能够建立多层目录 } // 3.把图片保存到SD卡 File filepic = new File(file, getFilename(url)); OutputStream out; try { out = new FileOutputStream(filepic); out.write(data); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * 保存图片方法二 * * @param url * @param data */ public static void saveImage(String url, Bitmap bitmap, int format) { // 一、判断是否有SD卡 if (!isSDMount()) { return; } // 2.判断是否有缓存的文件夹 File file = new File(SDCACHE_DIR); if (!file.exists()) { file.mkdirs();// 能够建立多层目录 } // 3.把图片保存到SD卡 File filepic = new File(file, getFilename(url)); try { OutputStream out = new FileOutputStream(filepic); // compress()将一个流转换为位图,并保存到SD卡 bitmap.compress((format == COMP_JPG ? CompressFormat.JPEG : CompressFormat.PNG), 100, out); } catch (FileNotFoundException e) { e.printStackTrace(); } } /** * 获取图片文件的名字 * * @param url * @return */ public static String getFilename(String url) { return url.substring(url.lastIndexOf("/") + 1);// http://xxxx/filename.jpg } public static Bitmap readImage(String url) { // 先判断SD是否挂载 if (!isSDMount()) { return null; } File file = new File(SDCACHE_DIR, getFilename(url)); if (file.exists()) { return BitmapFactory.decodeFile(file.getAbsolutePath()); } return null; } /** * 清空缓存目录 */ public void clearSDache() { File dir = new File(SDCACHE_DIR); File[] files = dir.listFiles(); for (File file : files) { file.delete(); } } /** * 生成缩略图的方法 * * @param filePath * @param newWidth * @param newHeight * @return */ public static Bitmap createThumbnail(String filePath, int newWidth, int newHeight) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true;// 该属性设为ture后,decodeFile并不分配空间,但可计算出原始图片的长度和宽度 // 目的:不生成bitmap数据,可是要获取原图的参数值 BitmapFactory.decodeFile(filePath, options); // 原图宽 int originalWidth = options.outWidth; // 原图高 int originalHeight = options.outHeight; // 按比例缩小宽高 int ratioWidth = originalWidth / newWidth; int ratioHeigth = originalHeight / newHeight; // inSampleSize=4这个值很重要,也就是宽高的四分之一计时十六分之一缩小图片 options.inSampleSize = ratioHeigth > ratioWidth ? ratioHeigth : ratioWidth; options.inJustDecodeBounds = false; // 注意这里要把options.inJustDecodeBounds设为false时才能从新分配图片空间 return BitmapFactory.decodeFile(filePath, options); } /** * 将文件(byte[])保存进sdcard指定的路径下 */ public static boolean saveFileToSDCard(byte[] data, String dir, String filename) { BufferedOutputStream bos = null; if (isSDMount()) { File file = new File(getSDCRRDDIR() + File.separator + dir); Log.i(TAG, "==file:" + file.toString() + file.exists()); if (!file.exists()) { boolean flags = file.mkdirs(); Log.i(TAG, "==建立文件夹:" + flags); } try { bos = new BufferedOutputStream(new FileOutputStream(new File( file, filename))); bos.write(data, 0, data.length); bos.flush(); return true; } catch (Exception e) { e.printStackTrace(); } finally { try { bos.close(); } catch (IOException e) { e.printStackTrace(); } } } return false; } /** * 已知文件的路径,从sdcard中获取到该文件,返回byte[] */ public static byte[] loadFileFromSDCard(String filepath) { BufferedInputStream bis = null; ByteArrayOutputStream baos = null; if (isSDMount()) { File file = new File(filepath); if (file.exists()) { try { baos = new ByteArrayOutputStream(); bis = new BufferedInputStream(new FileInputStream(file)); byte[] buffer = new byte[1024 * 8]; int c = 0; while ((c = bis.read(buffer)) != -1) { baos.write(buffer, 0, c); baos.flush(); } return baos.toByteArray(); } catch (Exception e) { e.printStackTrace(); } finally { try { if (bis != null) { bis.close(); baos.close(); } } catch (IOException e) { e.printStackTrace(); } } } } return null; } }