我正在开发一个应用程序,希望从URL下载图片。我需要一次性下载这些图像并将其存储到内部存储中。有200多张图片需要下载,请告诉我以最短的时间下载这些图片的最佳方法。如果有任何第三方库可用,请告诉我。
我正在开发一个应用程序,希望从URL下载图片。我需要一次性下载这些图像并将其存储到内部存储中。有200多张图片需要下载,请告诉我以最短的时间下载这些图片的最佳方法。如果有任何第三方库可用,请告诉我。
考虑使用Picasso来满足你的需求。我在我的项目中使用它。如果要将图像保存到外部磁盘上,可以使用以下代码:
Picasso.with(mContext)
.load(ImageUrl)
.into(new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
try {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/yourDirectory");
if (!myDir.exists()) {
myDir.mkdirs();
}
String name = new Date().toString() + ".jpg";
myDir = new File(myDir, name);
FileOutputStream out = new FileOutputStream(myDir);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch(Exception e){
// some action
}
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
}
);
从这里您可以下载这个库。
您可以从以下类似的URL下载图像:
URL url = new URL("http://www.yahoo.com/image_to_read.jpg");
InputStream in = new BufferedInputStream(url.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1!=(n=in.read(buf)))
{
out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
如果您想保存图像,可以执行以下操作:
FileOutputStream fos = new FileOutputStream("C://borrowed_image.jpg");
fos.write(response);
fos.close();
BitmapDrawable bitmapDrawable = (BitmapDrawable) holder.post_image.getDrawable();
Bitmap bitmap = bitmapDrawable.getBitmap();
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
MediaStore.Images.Media.insertImage(mContext.getContentResolver(), bitmap, "IMG_" + Calendar.getInstance().getTime(), null);
这是一个相当简单的任务...
const actionDownloadImage = (urls) => {
urls.map((url) => {
const splitUrl = url.split("/");
const filename = splitUrl[splitUrl.length - 1];
fetch(url)
.then((response) => {
response.arrayBuffer().then(function (buffer) {
const url = window.URL.createObjectURL(new Blob([buffer]));
const link = document.createElement("a");
link.href = url;
link.setAttribute("download", filename); //or any other extension
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});
})
.catch((err) => {
console.log(err);
});
});
}