欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

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

程序员文章站 2022-06-30 08:34:00
本文介绍了glide实现超简单的图片下载功能,具体步骤如下: 添加依赖 compile 'com.github.bumptech.glide:glide:3...

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

添加依赖

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

添加权限

 <uses-permission android:name="android.permission.internet"/>
 <uses-permission android:name="android.permission.write_external_storage"/>
<uses-permission android:name="android.permission.read_external_storage"/>

工具类代码

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<byte[]>() {
      @override
      public void onresourceready(byte[] bytes, glideanimation<? super byte[]> 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);

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

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