Glide下载图片并保存到本地

活不多说 上代码:

 Observable.create(new ObservableOnSubscribe() {
        @Override
        public void subscribe(ObservableEmitter 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() {
        @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

你可能感兴趣的:(Glide下载图片并保存到本地)