Skip to content

Instantly share code, notes, and snippets.

@RaulitoGC
Forked from yushaojian13/ImageSaveTask.java
Created June 6, 2018 18:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RaulitoGC/f06e6bb0405fcb9aae6f1a6a6538d42a to your computer and use it in GitHub Desktop.
Save RaulitoGC/f06e6bb0405fcb9aae6f1a6a6538d42a to your computer and use it in GitHub Desktop.
A task to download and save image to SD card with Glide
public class ImageSaveTask extends AsyncTask<String, Void, Void> {
private Context context;
public ImageSaveTask(Context context) {
this.context = context;
}
@Override
protected Void doInBackground(String... params) {
if (params == null || params.length < 2) {
throw new IllegalArgumentException("You should offer 2 params, the first for the image source url, and the other for the destination file save path");
}
String src = params[0];
String dst = params[1];
try {
File file = Glide.with(context)
.load(src)
.downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
.get();
File dstFile = new File(dst);
if (!dstFile.exists()) {
boolean success = dstFile.createNewFile();
if (!success) {
return null;
}
}
InputStream in = null;
OutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream(file));
out = new BufferedOutputStream(new FileOutputStream(dst));
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.flush();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
} catch (InterruptedException | ExecutionException | IOException e) {
e.printStackTrace();
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment