package com.allen.utils;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.util.Log;
public class Utils {
/**
* 获取网络中图片资源
* @param src 图片地址
* @return drawable对象
*/
public static Drawable loadImage(String src){
URL url=null;
try {
url = new URL(src);
} catch (MalformedURLException e) {
Log.e("-Utils-->MalformedURLExcetion--", e.toString());
}
InputStream is=null;
try {
is = url.openStream();
} catch (IOException e) {
Log.e("-Utils-->IOException--", e.toString());
}
Drawable drawable=Drawable.createFromStream(is, "img");
return drawable;
}
/**
* 从网络上下载
* @param url
* @return
*/
public static Bitmap getBitMapFromUrl(String url) {
Bitmap bitmap = null;
URL u =null;
HttpURLConnection conn = null;
InputStream is = null;
try {
u = new URL(url);
conn = (HttpURLConnection)u.openConnection();
is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
/**
* 从缓存中读取
* @param url
* @return
* @throws Exception
*/
public static Bitmap getImgFromCache(String url,Map<String,SoftReference<Bitmap>> imgCache) throws Exception {
Bitmap bitmap = null;
//从内存中读取
if(imgCache.containsKey(url)) {
synchronized (imgCache) {
SoftReference<Bitmap> bitmapReference = imgCache.get(url);
if(null != bitmapReference) {
bitmap = bitmapReference.get();
}
}
} else {//從網絡中下載
bitmap = getBitMapFromUrl(url);
//将图片保存进内存中
imgCache.put(url, new SoftReference<Bitmap>(bitmap));
}
return bitmap;
}
}