网站上的图标的获取,如百度的图标 的获取是在网站后面添加 /favicon.ico,如 https://i-blog.csdnimg.cn/blog_migrate/5a6639075515a8e27e0b1336db2300c1.png 。
在android中获取网络上的图片并存储到本地,或者置于ImageView组件中.以下为获取URL上的图标并设置到ImageView的工具方法:
public static void getBitmapFromURL(final String url, final ImageView imageView, final Handler handler){
new Thread(new Runnable() {
@Override
public void run() {
try {
URL httpURL = new URL(url);
HttpURLConnection conn = (HttpURLConnection) httpURL.openConnection();
conn.setReadTimeout(5000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
InputStream in = conn.getInputStream(); // 获取输入流
FileOutputStream out = null; // 输出流
File file = null; // 从URL下载的文件
String fileName = url.replace("/", "").replace(":", "").replace("&", ""); // 用URL作为文件名,将其中的特殊字符去除
// 判断 SD卡是否存在
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
File dir= Environment.getExternalStorageDirectory(); // 获取文件夹路径
file = new File(dir, fileName); // 获取到文件
out = new FileOutputStream(file); // 将文件写到本地存储
}
byte[] b = new byte[1024]; // 设置缓冲区大小
int length;
if(out != null) {
while((length = in.read(b)) != -1) {
out.write(b, 0, length); // 写入本地存储卡中
}
}
final Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath()); // 获取文件所在的位置
handler.post(new Runnable() {
@Override
public void run() {
imageView.setImageBitmap(bitmap);
}
});
file.delete(); // 置于ImageView组件后,将SD卡上的图标文件删除
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}