在Android中,可以使用第三方库来将网络图片加载到本地。其中最常用的库包括Glide和Picasso。以下是使用Glide加载网络图片到本地的示例代码:

1. 在build.gradle文件中添加Glide库的依赖:
java
implementation 'com.github.bumptech.glide:glide:4.12.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.12.0'
2. 在代码中使用Glide加载网络图片到本地:
java
String imgUrl = "https://www.example.com/image.jpg";
File localFile = new File(getCacheDir(), "image.jpg");
Glide.with(this)
.downloadOnly()
.load(imgUrl)
.listener(new RequestListener
@Override
public boolean onLoadFailed(@Nullable GlideException e, Object model, Target
return false;
}
@Override
public boolean onResourceReady(File resource, Object model, Target
// 如果加载成功,将图片保存到本地文件
try {
InputStream in = new FileInputStream(resource);
OutputStream out = new FileOutputStream(localFile);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
})
.submit();
在这个示例中,我们使用Glide的`downloadOnly()`方法加载网络图片,并在加载成功回调中将图片保存到本地文件。要确保添加了读写存储权限。
请注意,以上示例中使用了Glide 4版本。如果你使用的是其他版本,代码可能会有所不同。

查看详情

查看详情