Glide下载图片并保存到本地

一、前言:

我们在视频直播时,展示背景图片,经常由于网络较差,展示背景图片失败,所以提前把图片缓存到本地。

最后需要注意的下载保存需要读写权限,6.0以上需手动申请权限

android.permission.WRITE_EXTERNAL_STORAGE
android.permission.READ_EXTERNAL_STORAGE

二、下载过程:

1. 调用

 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()))));
        }
    });

2. 带上复制文件的方法:

/**
     * 复制文件
     *
     * @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();
            }
        }
    }


原文链接:https://blog.csdn.net/asswc2004/article/details/80537255

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

相关阅读更多精彩内容

友情链接更多精彩内容