杨充
2019-06-13
836浏览量
业务需求
具体做法代码展示
//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);
}
}
遇到的问题
为什么会遇到这种问题
那么如何解决问题呢?
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();
}
}
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();
}
}
}
思路:循环子线程
不建议的方案
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();
}
//刷新相册代码省略……
}
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
集结各类场景实战经验,助你开发运维畅行无忧