package com.wasu.cs.image;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;

import com.wasu.module.log.WLog;

public class MyImageLoader {

	// 从网络上取数据方法
	public static Bitmap loadImageFromUrl(String imageUrl) {

		try {

			return BitmapFactory.decodeStream(getImageStream(imageUrl));
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	private static InputStream getImageStream(String path) throws Exception {
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(5 * 1000);
		conn.setRequestMethod("GET");
		if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
			return conn.getInputStream();
		}
		return null;
	}

	/**
	 * 保存图片
	 * 
	 * @param bm
	 * @param fileName
	 * 
	 */
	public static void saveFile(Context context, Bitmap bm, String fileName) {
		try {
			boolean sdCardExist = Environment.getExternalStorageState().equals(
					android.os.Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
			String path;
			if (sdCardExist) {

				path = context.getExternalCacheDir().getPath();

			} else {

				path = context.getCacheDir().getPath();
			}
			// 缓存文件夹
			File dirFile = new File(path);
			if (!dirFile.exists()) {
				dirFile.mkdirs();
			}
			// 缓存图片
			File file = new File(path + "/" + fileName);
			if (file.exists()) {
				file.delete();
			}
			file.createNewFile();

			BufferedOutputStream bos = new BufferedOutputStream(
					new FileOutputStream(file));
			bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);
			bos.flush();
			bos.close();

		} catch (Exception e) {
			e.printStackTrace();
			WLog.e("echo", "保存文件异常" + e.toString());
		}
	}

	/**
	 * 使用存储的图片
	 * 
	 */
	public static Bitmap useTheImage(Context context, String fileName) {

		Bitmap bmp = null;
		boolean sdCardExist = Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
		String path;
		if (sdCardExist) {
			path = context.getExternalCacheDir().getPath();
		} else {
			path = context.getCacheDir().getPath();
		}

		File file = new File(path + "/" + fileName);
		bmp = BitmapFactory.decodeFile(file.getPath(), null);
		return bmp;

	}

}