Glide下载图片并保存到本地

活不多说 上代码:

 Observable.create(new ObservableOnSubscribe<File>() {
        @Override
        public void subscribe(ObservableEmitter<File> e) throws Exception {
            //通过gilde下载得到file文件,这里需要注意android.permission.INTERNET权限
            e.onNext(Glide.with(mContext)
                    .load(imagePathList.get(currentViewPosition).getPath())
                    .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                    .get());
            e.onComplete();
        }
    }).subscribeOn(Schedulers.io())
            .observeOn(Schedulers.newThread())
            .subscribe(new Consumer<File>() {
        @Override
        public void accept(File file) throws Exception {
            //获取到下载得到的图片,进行本地保存
            File pictureFolder = Environment.getExternalStorageDirectory();
            //第二个参数为你想要保存的目录名称
            File appDir = new File(pictureFolder, "your_picture_save_path");
            if (!appDir.exists()) {
                appDir.mkdirs();
            }
            String fileName = System.currentTimeMillis() + ".jpg";
            File destFile = new File(appDir, fileName);
            //把gilde下载得到图片复制到定义好的目录中去
            copy(file, destFile);
 
            // 最后通知图库更新
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                    Uri.fromFile(new File(destFile.getPath()))));
        }

});

带个复制文件的代码:

/**
    * 复制文件
    *
    * @param source 输入文件
    * @param target 输出文件
    */
   public void copy(File source, File target) {
       FileInputStream fileInputStream = null;
       FileOutputStream fileOutputStream = null;
       try {
           fileInputStream = new FileInputStream(source);
           fileOutputStream = new FileOutputStream(target);
           byte[] buffer = new byte[1024];
           while (fileInputStream.read(buffer) > 0) {
               fileOutputStream.write(buffer);
           }
       } catch (Exception e) {
           e.printStackTrace();
       } finally {
           try {
               fileInputStream.close();
               fileOutputStream.close();
           } catch (IOException e) {
               e.printStackTrace();
           }
       }
   }

注意要加权限:


最后需要注意的下载保存需要读写权限,6.0以后需手动申请权限
android.permission.WRITE_EXTERNAL_STORAGE
android.permission.READ_EXTERNAL_STORAGE

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • B.T 最近赵方舟感觉总有几双眼睛在背后盯着自己 我该不会是要被劫色了吧Σ(゚д゚lll) 下意识用手拉了拉衬衣 ...
    段宜恩de糖阅读 1,873评论 0 0
  • 说起 GIF 动图,你大概会想起聊天时「争图斗艳」的表情包吧,或者公众号里为了烘托气氛的配图。比起静态的图片,GI...
    CreativeMass阅读 10,421评论 2 7
  • 似玩笑,言语间诸多嬉闹 似嘲笑,真情不过这嬉闹 我俩的事,无人知晓,无人能懂,你也不明了 只我能晓,偏我明了,独我...
    暮色长安阅读 2,778评论 3 4

友情链接更多精彩内容