android从本地缓存和网络加载图片

本文介绍了一种从网络加载图片并缓存到本地的方法,包括获取网络路径、建立URL连接、读取输入流及使用输出流将数据写入文件等步骤。同时,通过判断本地是否存在缓存来提高加载效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、实现的思路
1、获取网络地址path
2、建立url对象
3、建立url连接conn
4、设置conn的连接方法
5、获取conn的输入流
7、new一个byte[] 数组
8、建立一个本地的文件File,并获取file的outputstream
9、用outputstream将byte[]写入到文件中
10、bitmapfactory.decodefile(),获取bitmap对象,并显示到图片控件上。

二、代码

 public void loadImg(){
    String path="http://192.168.2.101:8080/ppa_web/image/wsn.jpg";
    File file =new File(getCacheDir(), getFileName(path));
    if (file.exists()) {
        System.out.println("从本地缓存加载图片");
        Bitmap bp=BitmapFactory.decodeFile(file.getAbsolutePath());

            Message msg=new Message();
            msg.obj=bp;
            Handler.sendMessage(msg);

    }else {
      System.out.println("从网络加载图片");
            try {
                URL url = new URL(path);
                HttpURLConnection conn=(HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setReadTimeout(5000);
                conn.setConnectTimeout(5000);
                conn.connect();
                if (conn.getResponseCode()==200) {
                    InputStream is=conn.getInputStream();

                    FileOutputStream fos=new FileOutputStream(file);
                    byte[] b=new byte[1024];
                    int len;
                    while ((len=is.read(b))!=-1) {
                    fos.write(b, 0, len);
              }
                Bitmap bp=BitmapFactory.decodeFile(file.getAbsolutePath());

                Message msg=new Message();
                msg.obj=bp;
                Handler.sendMessage(msg);
        }else {
        Toast.makeText(this, "访问网络失败", 2000).show();
        }

            } catch (MalformedURLException e) {
            e.printStackTrace();
            } catch (IOException e) {
            e.printStackTrace();
            }
        }
    }

    //根据网络地址获取文件名称
      private String getFileName(String path) {
      int index=path.lastIndexOf("/");
      return path.substring(index);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值