//功能:將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; } }