Bitmap对象

Android系统分配给每个应用程序的内存是有限的,Bitmap作为消耗内存大户,我们对Bitmap的管理稍有不当就可能引发OutOfMemoryError,而Bitmap对象在不同的Android版本中存在一些差异。这里先简单记录下常见使用情景。

一、获取Bitmap对象

1.以R文件的方式(图片存在res下的drawable文件夹中)

Bitmap bitmap =BitmapFactory.decodeResource(getResources(), R.drawable.loading);

2.以文件流的方式(读取存储在手机上的图片)

FileInputStream fis = null;
try {
    fis = new FileInputStream(dir + "/" + fileName);
} catch (FileNotFoundException e) {
    e.printStackTrace();
}
Bitmap bitmap = BitmapFactory.decodeStream(fis);

FilutStr

3.通过网络url获取

URL url = new URL(imgUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream is = conn.getInputStream();
Bitmap bm = BitmapFactory.decodeStream(is);

二、将Bitmap保存为图片在手机上

public void SavaImage(Bitmap bitmap, String path,String fileName){
    File file=new File(path);
    //文件夹不存在,则创建它
    if(!file.exists()){
        file.mkdir();
    }
    FileOutputStream fileOutputStream=null;
    try {
        fileOutputStream=new FileOutputStream(path+"/"+fileName+".jpg");
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100,fileOutputStream);
        fileOutputStream.close();
        System.out.println("end save>>>>>>>");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值