android:读取SD卡中的图片显示出来(缩略图),SD卡工具类(13)

//功能:将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) {
		// 1、判断是否有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) {
		// 1、判断是否有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;
	}
}


转载于:https://my.oschina.net/u/2541146/blog/608619

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值