温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

android中Glide实现加载图片保存至本地并加载回调监听

发布时间:2020-09-15 11:25:29 来源:脚本之家 阅读:515 作者:code小生 栏目:移动开发

Glide 加载图片使用到的两个记录

Glide 加载图片保存至本地指定路径

/**
     * Glide 加载图片保存到本地
     *
     * imgUrl 图片地址
     * imgName 图片名称
     */
    Glide.with(context).load(imgUrl).asBitmap().toBytes().into(new SimpleTarget<byte[]>() {
      @Override
      public void onResourceReady(byte[] bytes, GlideAnimation<? super byte[]> glideAnimation) {
        try {
          savaBitmap(imgName, bytes);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    });

// 保存图片到手机指定目录
  public void savaBitmap(String imgName, byte[] bytes) {
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
      String filePath = null;
      FileOutputStream fos = null;
      try {
        filePath = Environment.getExternalStorageDirectory().getCanonicalPath() + "/MyImg";
        File imgDir = new File(filePath);
        if (!imgDir.exists()) {
          imgDir.mkdirs();
        }
        imgName = filePath + "/" + imgName;
        fos = new FileOutputStream(imgName);
        fos.write(bytes);
        Toast.makeText(context, "图片已保存到" + filePath, Toast.LENGTH_SHORT).show();
      } catch (IOException e) {
        e.printStackTrace();
      } finally {
        try {
          if (fos != null) {
            fos.close();
          }
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    } else {
      Toast.makeText(context, "请检查SD卡是否可用", Toast.LENGTH_SHORT).show();
    }
  }

Glide 加载图片回调方法

Glide.with(context).load(imgUrl)
        .listener(new RequestListener<String, GlideDrawable>() {
          @Override
          public boolean onException(Exception e, String model,
                        Target<GlideDrawable> target,
                        boolean isFirstResource) {
            // 可替换成进度条
            Toast.makeText(context, "图片加载失败", Toast.LENGTH_SHORT).show();
            return false;
          }

          @Override
          public boolean onResourceReady(GlideDrawable resource, String model,
                          Target<GlideDrawable> target,
                          boolean isFromMemoryCache,
                          boolean isFirstResource) {
            // 图片加载完成,取消进度条
            Toast.makeText(context, "图片加载成功", Toast.LENGTH_SHORT).show();
            return false;
          }
        }).error(R.mipmap.ic_launcher_round)
        .diskCacheStrategy(DiskCacheStrategy.ALL)
        .into(imageView);

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

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI