根据URL加载图片并付给bitmap(微信分享中使用)

原文网址: 

1. http://xiaxveliang.blog.163.com/blog/static/297080342013827768676/

2. http://kylines.iteye.com/blog/1660180


1、权限:

    1)联网权限
    2)图片存储到sdcard的权限

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>

2、根据给定URL,下载网络图片:

public Bitmap downloadPic(Context context, String pUrl) {
URL url = null;
HttpURLConnection conn = null;
InputStream is = null;
ByteArrayOutputStream baos = null;
Bitmap bitmap = null;
String filePath = null;
try {

if (bitmap == null) {

url = new URL(pUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setDoInput(true);
conn.connect();
is = conn.getInputStream();
baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
byte[] pArray = baos.toByteArray();

bitmap = BitmapFactory
.decodeByteArray(pArray, 0, pArray.length);

}

} catch (FileNotFoundException e) {
e.printStackTrace();
if (bitmap != null) {
bitmap.recycle();
bitmap = null;
}
} catch (IOException e) {
e.printStackTrace();
if (bitmap != null) {
bitmap.recycle();
bitmap = null;
}
} catch (OutOfMemoryError e) {
e.printStackTrace();
if (bitmap != null) {
bitmap.recycle();
bitmap = null;
}
} catch (Exception e) {
e.printStackTrace();
if (bitmap != null) {
bitmap.recycle();
bitmap = null;
}
} finally {

if (conn != null) {
conn.disconnect();
}
if (baos != null) {
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return bitmap;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值