public Drawable loadImageFromUrl(String urlPath, String directory,
String filename) {
byte[] data = null;
InputStream is = null;
Drawable drawable = null;
HttpURLConnection conn = null;
URL url = null;
try {
url = new URL(urlPath);
} catch (Exception e) {
e.printStackTrace();
return drawable;
}
try {
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
// conn.setDoOutput(true);
conn.setRequestMethod("GET");
conn.setConnectTimeout(6000);
is = conn.getInputStream();
if (conn.getResponseCode() == 200) {
BitmapFactory.Options opts = new BitmapFactory.Options();
data = readInputStream(is);
//处理图片溢出
opts.inJustDecodeBounds = true;
BitmapFactory.decodeByteArray(data, 0, data.length, opts);
opts.inSampleSize = computeSampleSize(opts, -1, AppContext.getScreenHeight()*AppContext.getScreenWidth());
opts.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0,
data.length, opts);
drawable = (Drawable) new BitmapDrawable(bitmap);
// 如果目录和图片名称存在,保存图片
if (null != directory && null != filename) {
// 创建目录,保存图片
if (hasStorage(true, directory)) {
// 目录地址
String directoryName = SDPATH + directory;
// 创建文件
File file = new File(directoryName, filename);
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(file));
// 获取图片的格式
String dat = filename.substring(filename
.lastIndexOf(".") + 1);
Log.d(TAG, "图片格式1111111111:" + dat);
if ("jpg".equals(dat)) {
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bos);
} else if ("png".equals(dat)) {
bitmap.compress(Bitmap.CompressFormat.PNG, 90, bos);
}
bos.flush();
bos.close();
} else {
Log.d(TAG, "save picture failed");
}
}
} else {
data = null;
}
} catch (Exception e) {
e.printStackTrace();
drawable = null;
} finally {
try {
if (is != null) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
conn.disconnect();
}
return drawable;
}