Android保存多张图片到本地的实现方法

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
 */
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();
  }
  //刷新相册代码省略……
 }
}

链接地址:https://github.com/yangchong2...

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对我们的支持。

(0)

相关推荐

  • Android实现保存图片到本地并在相册中显示

    Android中拍照保存图片到本地是常见的一种需求,之前碰到了一个问题,就是在4.4中,刷新相册会出现ANR,经过一番百度解决了这个问题. 首先是保存图片到本地 private static final String SAVE_PIC_PATH = Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_MOUNTED) ? Environment.getExternalStorageDirectory()

  • android中Glide实现加载图片保存至本地并加载回调监听

    Glide 加载图片使用到的两个记录 Glide 加载图片保存至本地指定路径 /** * Glide 加载图片保存到本地 * * imgUrl 图片地址 * imgName 图片名称 */ Glide.with(context).load(imgUrl).asBitmap().toBytes().into(new SimpleTarget<byte[]>() { @Override public void onResourceReady(byte[] bytes, GlideAnimation

  • Android长按imageview把图片保存到本地的实例代码

    工具类 之前用 AsyncTask 现在改用rxJava public class SaveImageUtils { public static void imageSave(final ImageView imageView, final int id) { Observable .create(new Observable.OnSubscribe<ImageView>() { @Override public void call(Subscriber<? super ImageVie

  • 基于Android实现保存图片到本地并可以在相册中显示出来

    App应用越来越人性化,不仅界面优美而且服务也很多样化,操作也非常方便.比如我们在用app的时候,发现上面有比较的图片想保存到手机,只要点一点app上提供的保存按钮就可以了.那这个图片保存到本地怎么实现的呢? 保存图片很简单,方法如下: /** 首先默认个文件保存路径 */ private static final String SAVE_PIC_PATH=Environment.getExternalStorageState().equalsIgnoreCase(Environment.MED

  • Android下保存简单网页到本地(包括简单图片链接转换)实现代码

    最近在做一个项目涉及到将包含图片的简单网页下载到本地,方便离线时观看,在这里分享一下,大家做下简单修改就可以用到自己的项目中了.(这里用到了AQuery库) 复制代码 代码如下: package com.nekocode.xuedao.utils; import java.io.File;import java.io.FileOutputStream;import java.util.ArrayList;import java.util.regex.Matcher;import java.uti

  • Android保存多张图片到本地的实现方法

    01.实际开发保存图片遇到的问题 业务需求 在素材list页面的九宫格素材中,展示网络请求加载的图片.如果用户点击保存按钮,则保存若干张图片到本地.具体做法是,使用glide加载图片,然后设置listener监听,在图片请求成功onResourceReady后,将图片资源resource保存到集合中.这个时候,如果点击保存控件,则循环遍历图片资源集合保存到本地文件夹. 具体做法代码展示 这个时候直接将请求网络的图片转化成bitmap,然后存储到集合中.然后当点击保存按钮的时候,将会保存该组集合中

  • ASP保存远程图片到本地 同时取得第一张图片并创建缩略图的代码

    采集中 或者 在线添加文章中 都可以用到此功能 俺自己在baidu上搜索的保存远程图片到本地的代码 感觉比较难用点 而且没有现成的比较全的代码 俺也看不懂 俺从 SNA新闻采集系统 For 3.62 (程序制作:ansir)里提取了点函数 用下 比较简单好用 以下是函数 程序代码  复制代码 代码如下: <% '================================================== '函数名:CheckDir2 '作 用:检查文件夹是否存在 '参 数:FolderP

  • Android studio保存logcat日志到本地的操作

    windows环境下 1.输出logcat日志到本地文件 adb logcat -> F:/logcat.txt 2.输出带时间的logcat日志到本地文件: adb logcat -v threadtime -> F:/logcat.txt 输入以上命令后,adb自动保存logcat日志到指令的文件,,按ctrl + c结束保存. 补充知识:Android真机调试不打印log Android开发过程中,有时候用真机调试时明明执行了log打印,但是控制台就是不输出,可能是因为手机的log打印功

  • Android保存App异常信息到本地

    本文实例为大家分享了Android保存App异常信息到本地的具体代码,供大家参考,具体内容如下 首先添加权限 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> 代码 // 调用该方法造成异常 private void math() { try { int a = 0; int b = 10; int c = b / a; } catch (Exception e) { e.

  • Android 保存文件路径方法

    Android保存文件到本地路径问题 常见路径 例如: application 包名: com.my.company 项目名: chat /data/data == ///data/user/0 getExternalFilesDir()方法可以获取到 SDCard/Android/data/你的应用的包名/files/ 目录, 一般放一些长时间保存的数据 getExternalCacheDir()方法可以获取到 SDCard/Android/data/你的应用包名/cache/目录, 一般存放

  • android 拷贝sqlite数据库到本地sd卡的方法

    sqlite小型数据库,在开发的时候用于保存数据,在这不做关于它的介绍,本文只是写出了怎么拷贝应用的数据到本地sd卡中.如:一个数据库名为dandy.db的,拷贝到本地中叫seeker.db 代码如下: /** * 拷贝数据库到sd卡 * * @deprecated <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> */ public static void copyDat

  • Android远程获取图片并本地缓存

    对于客户端--服务器端应用,从远程获取图片算是经常要用的一个功能,而图片资源往往会消耗比较大的流量,对应用来说,如果处理不好这个问题,那会让用户很崩溃,不知不觉手机流量就用完了,等用户发现是你的应用消耗掉了他手机流量的话,那么可想而知你的应用将面临什么样的命运. 另外一个问题就是加载速度,如果应用中图片加载速度很慢的话,那么用户同样会等到崩溃. 那么如何处理好图片资源的获取和管理呢? *异步下载 *本地缓存 1.异步下载: 大家都知道,在android应用中UI线程5秒没响应的话就会抛出无响应异

  • Android实现搜索本地音乐的方法

    本文实例为大家分享了Android实现搜索本地音乐展示的具体代码,供大家参考,具体内容如下 首先是扫描本地所有的音频文件,然后全部装进集合当中,接下来就是用ListView展示在屏幕上,大概就是这几个步骤了,接下来细讲 创建一个容器 进行过数据解析的朋友都应该知道JavaBean吧,用来装载解析出来的数据,我们这里同样也要创建一个JavaBean,用来装载扫描到的音频文件,具体的代码是: /** * Created by user on 2016/6/24. * 放置音乐 */ public c

  • Android studio 将字符串写入本地的操作方法

    File 类的操作: 1.首先需要添加相关权限: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/> 注意6.0以上需要动态申请: private void checkPermission(){

  • Android开发实现加载网络图片并下载至本地SdCard的方法

    本文实例讲述了Android开发实现加载网络图片并下载至本地SdCard的方法.分享给大家供大家参考,具体如下: package com.example.myimagedemo; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; imp

随机推荐