溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

android中Glide實現加載圖片保存至本地并加載回調監聽

發布時間:2020-09-15 11:25:29 來源:腳本之家 閱讀:578 作者: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

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女