栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 移动开发 > Android

Android中Glide实现超简单的图片下载功能

Android 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Android中Glide实现超简单的图片下载功能

本文介绍了Glide实现超简单的图片下载功能,具体步骤如下:

添加依赖

compile 'com.github.bumptech.glide:glide:3.7.0'

添加权限

 
 

工具类代码

public class SDFileHelper {

  private Context context;

  public SDFileHelper() {
  }

  public SDFileHelper(Context context) {
    super();
    this.context = context;
  }

  //Glide保存图片
  public void savePicture(final String fileName, String url){
    Glide.with(context).load(url).asBitmap().toBytes().into(new SimpleTarget() {
      @Override
      public void onResourceReady(byte[] bytes, GlideAnimation glideAnimation) {
 try {
   savaFileToSD(fileName,bytes);
 } catch (Exception e) {
   e.printStackTrace();
 }
      }
    });
  }
  //往SD卡写入文件的方法
  public void savaFileToSD(String filename, byte[] bytes) throws Exception {
    //如果手机已插入sd卡,且app具有读写sd卡的权限
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
      String filePath = Environment.getExternalStorageDirectory().getCanonicalPath()+"/budejie";
      File dir1 = new File(filePath);
      if (!dir1.exists()){
 dir1.mkdirs();
      }
      filename = filePath+ "/" + filename;
      //这里就不要用openFileOutput了,那个是往手机内存中写数据的
      FileOutputStream output = new FileOutputStream(filename);
      output.write(bytes);
      //将bytes写入到输出流中
      output.close();
      //关闭输出流
      Toast.makeText(context, "图片已成功保存到"+filePath, Toast.LENGTH_SHORT).show();
    } else Toast.makeText(context, "SD卡不存在或者不可读写", Toast.LENGTH_SHORT).show();
  }

}

然后再需要的地方调用

 SDFileHelper helper = new SDFileHelper(MainActivity.this);
 helper.savePicture("bg.jpg",url);


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/159212.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号