目录介绍

  • 01.实际开发保存图片遇到的问题
  • 02.直接用http请求图片并保存本地
  • 03.用glide下载图片保存本地
  • 04.如何实现连续保存多张图片
  • 05.关于其他介绍

好消息

  • 博客笔记大汇总【16年3月到至今】,包括Java基础及深入知识点,Android技术博客,Python学习笔记等等,还包括平时开发中遇到的bug汇总,当然也在工作之余收集了大量的面试题,长期更新维护并且修正,持续完善……开源的文件是markdown格式的!同时也开源了生活博客,从12年起,积累共计N篇[近100万字,陆续搬到网上],转载请注明出处,谢谢!
  • 链接地址:https://github.com/yangchong211/YCBlogs
  • 如果觉得好,可以star一下,谢谢!当然也欢迎提出建议,万事起于忽微,量变引起质变!

01.实际开发保存图片遇到的问题

  • 业务需求

    • 在素材list页面的九宫格素材中,展示网络请求加载的图片。如果用户点击保存按钮,则保存若干张图片到本地。具体做法是,使用glide加载图片,然后设置listener监听,在图片请求成功onResourceReady后,将图片资源resource保存到集合中。这个时候,如果点击保存控件,则循环遍历图片资源集合保存到本地文件夹。
  • 具体做法代码展示
    • 这个时候直接将请求网络的图片转化成bitmap,然后存储到集合中。然后当点击保存按钮的时候,将会保存该组集合中的多张图片到本地文件夹中。
    //bitmap图片集合
    private ArrayList<Bitmap> bitmapArrayList = new ArrayList<>();RequestOptions requestOptions = new RequestOptions() .transform(new GlideRoundTransform(mContext, radius, cornerType)); GlideApp.with(mIvImg.getContext()) .asBitmap() .load(url) .listener(new RequestListener<Bitmap>() { @Override public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Bitmap> target, boolean isFirstResource) { return true; } @Override public boolean onResourceReady(Bitmap resource, Object model, Target<Bitmap> target, DataSource dataSource, boolean isFirstResource) { bitmapArrayList.add(resource); return false; } }) .apply(requestOptions) .placeholder(ImageUtils.getDefaultImage()) .into(mIvImg); //循环遍历图片资源集合,然后开始保存图片到本地文件夹 mBitmap = bitmapArrayList.get(i); savePath = FileSaveUtils.getLocalImgSavePath(); FileOutputStream fos = null; try { File filePic = new File(savePath); if (!filePic.exists()) { filePic.getParentFile().mkdirs(); filePic.createNewFile(); } fos = new FileOutputStream(filePic); // 100 图片品质为满 mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos); } catch (IOException e) { e.printStackTrace(); return null; } finally { if (fos != null) { try { fos.flush(); fos.close(); } catch (IOException e) { e.printStackTrace(); } } //刷新相册 if (isScanner) { scanner(context, savePath); } } 
  • 遇到的问题
    • 保存图片到本地后,发现图片并不是原始的图片,而是展现在view控件上被裁切的图片,也就是ImageView的尺寸大小图片。
  • 为什么会遇到这种问题
    • 如果你传递一个ImageView作为.into()的参数,Glide会使用ImageView的大小来限制图片的大小。例如如果要加载的图片是1000x1000像素,但是ImageView的尺寸只有250x250像素,Glide会降低图片到小尺寸,以节省处理时间和内存。
    • 在设置into控件后,也就是说,在onResourceReady方法中返回的图片资源resource,实质上不是你加载的原图片,而是ImageView设定尺寸大小的图片。所以保存之后,你会发现图片变小了。
  • 那么如何解决问题呢?
    • 第一种做法:九宫格图片控件展示的时候会加载网络资源,然后加载图片成功后,则将资源保存到集合中,点击保存则循环存储集合中的资源。这种做法只会请求一个网络。由于开始
    • 第二种做法:九宫格图片控件展示的时候会加载网络资源,点击保存九宫格图片的时候,则依次循环请求网络图片资源然后保存图片到本地,这种做法会请求两次网络。

02.直接用http请求图片并保存本地

  • http请求图片

    /*** 请求网络图片* @param url                       url* @return                          将url图片转化成bitmap对象 */ private static long time = 0; public static InputStream HttpImage(String url) { long l1 = System.currentTimeMillis(); URL myFileUrl = null; Bitmap bitmap = null; HttpURLConnection conn = null; InputStream is = null; try { myFileUrl = new URL(url); } catch (MalformedURLException e) { e.printStackTrace(); } try { conn = (HttpURLConnection) myFileUrl.openConnection(); conn.setConnectTimeout(10000); conn.setReadTimeout(5000); conn.setDoInput(true); conn.connect(); is = conn.getInputStream(); } catch (IOException e) { e.printStackTrace(); } finally { try { if (is != null) { is.close(); conn.disconnect(); } } catch (IOException e) { e.printStackTrace(); } long l2 = System.currentTimeMillis(); time = (l2-l1) + time; LogUtils.e("毫秒值"+time); //保存 } return is; } 
  • 保存到本地
    InputStream inputStream = HttpImage("https://img1.haowmc.com/hwmc/material/2019061079934131.jpg");
    String localImgSavePath = FileSaveUtils.getLocalImgSavePath();
    File imageFile = new File(localImgSavePath); if (!imageFile.exists()) { imageFile.getParentFile().mkdirs(); try { imageFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } FileOutputStream fos = null; BufferedInputStream bis = null; try { fos = new FileOutputStream(imageFile); bis = new BufferedInputStream(inputStream); byte[] buffer = new byte[1024]; int len; while ((len = bis.read(buffer)) != -1) { fos.write(buffer, 0, len); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (bis != null) { bis.close(); } if (fos != null) { fos.close(); } } catch (IOException e) { e.printStackTrace(); } } 

03.用glide下载图片保存本地

  • glide下载图片

    File file = Glide.with(ReflexActivity.this).load(url.get(0)).downloadOnly(500, 500) .get(); 
  • 保存到本地
    String localImgSavePath = FileSaveUtils.getLocalImgSavePath();
    File imageFile = new File(localImgSavePath);
    if (!imageFile.exists()) {imageFile.getParentFile().mkdirs();imageFile.createNewFile();
    }
    copy(file,imageFile); /** * 复制文件 * * @param source 输入文件 * @param target 输出文件 */ public static 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 { if (fileInputStream != null) { fileInputStream.close(); } if (fileOutputStream != null) { fileOutputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } } 

04.如何实现连续保存多张图片

  • 思路:循环子线程

    • 可行(不推荐), 如果我要下载9个图片,将子线程加入for循环内,并最终呈现。
    • 有严重缺陷,线程延时,图片顺序不能做保证。如果是线程套线程的话,第一个子线程结束了,嵌套在该子线程f的or循环内的子线程还没结束,从而主线程获取不到子线程里获取的图片。
    • 还有就是如何判断所有线程执行完毕,比如所有图片下载完成后,吐司下载完成。
  • 不建议的方案
    • 创建一个线程池来管理线程,关于线程池封装库,可以看线程池简单封装
    • 这种方案不知道所有线程中请求图片是否全部完成,且不能保证顺序。
    ArrayList<String> images = new ArrayList<>();
    for (String image : images){ //使用该线程池,及时run方法中执行异常也不会崩溃 PoolThread executor = BaseApplication.getApplication().getExecutor(); executor.setName("getImage"); executor.execute(new Runnable() { @Override public void run() { //请求网络图片并保存到本地操作 } }); } 
  • 推荐解决方案
    ArrayList<String> images = new ArrayList<>();
    ApiService apiService = RetrofitService.getInstance().getApiService();
    //注意:此处是保存多张图片,可以采用异步线程
    ArrayList<Observable<Boolean>> observables = new ArrayList<>(); final AtomicInteger count = new AtomicInteger(); for (String image : images){ observables.add(apiService.downloadImage(image) .subscribeOn(Schedulers.io()) .map(new Function<ResponseBody, Boolean>() { @Override public Boolean apply(ResponseBody responseBody) throws Exception { saveIo(responseBody.byteStream()); return true; } })); } // observable的merge 将所有的observable合成一个Observable,所有的observable同时发射数据 Disposable subscribe = Observable.merge(observables).observeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer<Boolean>() { @Override public void accept(Boolean b) throws Exception { if (b) { count.addAndGet(1); Log.e("yc", "download is succcess"); } } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) throws Exception { Log.e("yc", "download error"); } }, new Action() { @Override public void run() throws Exception { Log.e("yc", "download complete"); // 下载成功的数量 和 图片集合的数量一致,说明全部下载成功了 if (images.size() == count.get()) { ToastUtils.showRoundRectToast("保存成功"); } else { if (count.get() == 0) { ToastUtils.showRoundRectToast("保存失败"); } else { ToastUtils.showRoundRectToast("因网络问题 保存成功" + count + ",保存失败" + (images.size() - count.get())); } } } }, new Consumer<Disposable>() { @Override public void accept(Disposable disposable) throws Exception { Log.e("yc","disposable"); } }); private void saveIo(InputStream inputStream){ String localImgSavePath = FileSaveUtils.getLocalImgSavePath(); File imageFile = new File(localImgSavePath); if (!imageFile.exists()) { imageFile.getParentFile().mkdirs(); try { imageFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } FileOutputStream fos = null; BufferedInputStream bis = null; try { fos = new FileOutputStream(imageFile); bis = new BufferedInputStream(inputStream); byte[] buffer = new byte[1024]; int len; while ((len = bis.read(buffer)) != -1) { fos.write(buffer, 0, len); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (bis != null) { bis.close(); } if (fos != null) { fos.close(); } } catch (IOException e) { e.printStackTrace(); } //刷新相册代码省略…… } } 

其他介绍

01.关于博客汇总链接

  • 1.技术博客汇总
  • 2.开源项目汇总
  • 3.生活博客汇总
  • 4.喜马拉雅音频汇总
  • 5.其他汇总

02.关于我的博客

  • github:https://github.com/yangchong211
  • 知乎:https://www.zhihu.com/people/yczbj/activities
  • 简书:http://www.jianshu.com/u/b7b2c6ed9284
  • csdn:http://my.csdn.net/m0_37700275
  • 喜马拉雅听书:http://www.ximalaya.com/zhubo/71989305/
  • 开源中国:https://my.oschina.net/zbj1618/blog
  • 泡在网上的日子:http://www.jcodecraeer.com/member/content_list.php?channelid=1
  • 邮箱:yangchong211@163.com
  • 阿里云博客:https://yq.aliyun.com/users/article?spm=5176.100- 239.headeruserinfo.3.dT4bcV
  • segmentfault头条:https://segmentfault.com/u/xiangjianyu/articles
  • 掘金:https://juejin.im/user/5939433efe88c2006afa0c6e

项目案例:https://github.com/yangchong211/YCVideoPlayer

转载于:https://www.cnblogs.com/yc211/p/11015795.html

Android保存多张图片到本地相关推荐

  1. Android保存配置文件内容到本地(txt、xml两种)

    在做项目的时候难免需要保存一下配置文件,我们经常使用的就是SharedPreferences,但是当我们清除掉缓存或者卸载后重新安装这些配置文件内容就不存在了,当我们想卸载后重新安装这些配置文件还在, ...

  2. Android 保存崩溃日志到本地目录下

    代码如下可以直接复制过去,别人的代码修改了下 package com.hly.rtxt; import android.annotation.SuppressLint; import android. ...

  3. java保存多张图片格式_从多个URL下载多个图像文件并保存到本地计算机(使用R)...

    我试图从网址下载jpeg图像文件并保存在我的本地笔记本电脑中 . (我正在使用R) . 我从R中的一个url找到了一个图像文件的解决方案,它实际上工作得很好 . y = "http://ec ...

  4. android studio 抓log,Android studio保存logcat日志到本地的操作

    windows环境下 1.输出logcat日志到本地文件 adb logcat -> F:/logcat.txt 2.输出带时间的logcat日志到本地文件: adb logcat -v thr ...

  5. php文章远程图片,php保存远程图片到本地 php正则匹配文章中的远程图片地址

    在添加文章的时候,很多情况下我们需要处理文章中的远程图片,将其保存到本地,以免别人网站删除后文章里面就无法访问了. 因此我们需要正则匹配文章中的图片地址, 这里我们使用php的正则表达式来实现:$co ...

  6. Android中一张图片占用的内存大小

    最近面试过程中发现对Android中一些知识有些模棱两可,之前总是看别人的总结,自己没去实践过,这两天对个别问题进行专门研究 探讨:如何计算Android中一张图片占据内存的大小 解释:此处说的占据内 ...

  7. android.mk遍历子目录,android 保存文件的各种目录列表

    一般的,我们可以通过context和Environment来获取要保存文件的目录 ($rootDir) +- /data -> Environment.getDataDirectory() | ...

  8. android相册拍照保存图片到本地

    功能:选择相册或者拍照图片保存到本地,下次打开程序直接显示,图片可裁剪. 一.新建布局: <?xml version="1.0" encoding="utf-8&q ...

  9. android 浏览器打开本地html文件,如何在Android浏览器中加载本地HTML文件

    我试图在设备浏览器中加载本地html文件.我尝试过使用WebView,但它不适用于所有设备.如何在Android浏览器中加载本地HTML文件 //WebView method that didnt w ...

  10. C# .NET 根据Url链接保存Image图片到本地磁盘

    C# .NET 根据Url链接保存Image图片到本地磁盘 原文:C# .NET 根据Url链接保存Image图片到本地磁盘 根据一个Image的Url链接可以在浏览器中显示一个图片,如果要通过代码将 ...

最新文章

  1. 张艾迪(创始人): 梦想与未来
  2. 时间序列预测之三:频谱分析(二)
  3. Linux—vim常用命令
  4. 同IP不同端口Session冲突问题
  5. flask 实现异步非阻塞----gevent
  6. JavaScript学习总结(15)——十大经典排序算法的JS版
  7. 如何成为一名Web前端开发人员?入行学习完整指南
  8. Win10系统下面的TR1008解决方案
  9. VS code react插件快捷键
  10. 计算机绘图中常用指令,【CAD快捷键运用】CAD常用命令汇总
  11. 计算机学院审核评估方案,计算机与数据科学学院 本科教学工作审核评估迎评工作方案...
  12. 中国步进电机市场现状研究分析与发展前景预测报告(2022)
  13. java deflate解压_Java解压缩用zlib deflate压缩的字符串
  14. Java多功能计算器小程序
  15. 华工 计算机网络 第二次 作业,华工网络教育计算机网络作业及答案
  16. 网络创业者之家:写给新手的互联网创业干货,让你少走弯路
  17. windows7 安装vs2008 sp1出错的解决办法
  18. 网络带宽监控,带宽监控工具哪个好
  19. hubbledotnet mysql_HubbleDotNet开源全文搜索数据库项目--查询方法汇总
  20. 通过注册表修改IE选项 -- 高级选项里边的“关闭浏览器时清空“Internet临时文件”文件夹”的方法

热门文章

  1. 信息率失真函数matlab,基于MATLAB的信息率失真函数计算本科毕业论文.doc
  2. MySQL学习(一、概述和表的基本操作)
  3. 阿里云服务器centos7 安装docker 和docker-compose 及相关命令
  4. linux Flatpak 安装包,snap卸载
  5. PHP REDIS 使用长连接多数据库存储到最后一个数据库中的问题解决
  6. windows下php mongodb 安装配置使用查询
  7. LayaAir 图集动画2—动画运用
  8. SQL 高效运行注意事项(一)
  9. CSS3 结构性伪类选择器(1)
  10. 在64位系统中无法看到Microsoft Excel Application的问题