android下载网络图片,BitmapFactory创建bitmap

项目中有几个应用导航的链接,logo图,可能需要从网络上下载,因为是logo,所以用的png 透明格式。

在网上发现很多人提问,BitmapFactory.decondeXXXX 方法生成图片,透明度会消失.我不知道别人用的可能是imageView,我用imageButton可以实现的,补充下,我用imageview测试,也是可以保持透明度的。

1,通过网络下载图片。

URL url = new URL(tempImgUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(8000);
conn.connect();


BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
bitmapOptions.inScreenDensity = metrics.densityDpi;
bitmapOptions.inTargetDensity =  metrics.densityDpi;
bitmapOptions.inDensity = DisplayMetrics.DENSITY_DEFAULT;

Bitmap bitmap = BitmapFactory.decodeStream(conn.getInputStream(), null, bitmapOptions);

加粗部分很重要,必须使用这个三参数的函数,因为该函数,还有一个只需要inputstream。

标红部分是根据density来自动放大缩小图片。

2. 显示图片

imageButton.setImageBitmap(bitmap )

3. 缓存图片

public static byte[] bitmap2BytesPng(Bitmap bm) {
ByteArrayOutputStream bas = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, bas);
return bas.toByteArray();
}

public static void saveImage(String imagePath, byte[] buffer) throws IOException {
File f = new File(imagePath);
if (f.exists()) {
return;
} else {
File parentFile = f.getParentFile();
if (!parentFile.exists()) {
parentFile.mkdirs();
}
f.createNewFile();
FileOutputStream fos = new FileOutputStream(imagePath);
fos.write(buffer);
fos.flush();
fos.close();
}
}


saveImage(imagePath, bitmap2BytesPng(bitmap));

4.下次使用时
File file = new File(imagePath);
if (file.exists()) {
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
file.setLastModified(System.currentTimeMillis());
return bitmap;
}

这样就可以实现下载图片保留透明度了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值