Android Glide下载图片到本地(相册中)

37次阅读
没有评论
/**
* 下载到本地
* @param context 上下文
* @param url 网络图
*/
private void saveImgToLocal(Context context, String url) {
//如果是网络图片,抠图的结果,需要先保存到本地
Glide.with(context)
.downloadOnly()
.load(url)
.listener(new RequestListener<file>() {
@Override
public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<file> target, boolean isFirstResource) {
Toast.makeText(context, "下载失败", Toast.LENGTH_SHORT).show();
return false;
}</file></file>

@Override
public boolean onResourceReady(File resource, Object model, Target<file> target, DataSource dataSource, boolean isFirstResource) {
Toast.makeText(context, "下载成功", Toast.LENGTH_SHORT).show();
saveToAlbum(context, resource);
return false;
}
})
.preload();
}</file>

private void saveToAlbum(Context context, File resource) {
String dcimPath = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM).getAbsolutePath();
File file = new File(dcimPath, "content_" + System.currentTimeMillis() + ".png");
boolean isCopySuccess = copy(resource, file);
if (isCopySuccess) {
//发送广播通知
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getAbsolutePath())));
Toast.makeText(this,"保存成功",Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this,"保存失败",Toast.LENGTH_SHORT).show();
}
}

private boolean copy(File source, File target) {
boolean status = true;
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();
status = false;
} finally {
try {
fileInputStream.close();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return status;
}
迷鹿, lostfawn
版权声明:本站原创文章,由迷鹿, lostfawn2021-10-08发表,共计1631字。
转载提示:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)
载入中...
召唤伊斯特瓦尔