在前一篇博客笔记HttpURLConnection下载网络图片中学习了下载并显示网络上的一张图片,在此基础上怎么保存该网络图片,关键代码如下:
private void downloadPicture(){
String urlStr = "https://img-my.youkuaiyun.com/uploads/201407/26/1406383291_6518.jpg";
HttpURLConnection conn = null;
BufferedInputStream bis = null;
File imageFile = null;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5 * 1000);//设置网络连接超时
conn.setReadTimeout(10 * 1000);//设置读取数据超时
conn.setDoInput(true);//设置是否从httpUrlConnection读入,默认情况下是true;
/*
*设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在
*http正文内,因此需要设为true, 默认情况下是false;
*/
conn.setDoOutput(true);
InputStream in = conn.getInputStream();
Bitmap bm = BitmapFactory.decodeStream(in);
//保存该图片到指定的目录
bis = new BufferedInputStream(conn.getInputStream());
imageFile = new File(getImagePath(urlStr));
fos = new FileOutputStream(imageFile);
bos = new BufferedOutputStream(fos);
byte[] b = new byte[1024];
int length;
while ((length = bis.read(b)) != -1) {
bos.write(b, 0, length);
bos.flush();
}
/* 1、android子线程不能更新主线程创建的组件解决方法
*
* 2、如果强制使用 imageview.setImageBitmap(bitmap);
* 则会报错 android.view.ViewRootImpl$CalledFromWrongThreadException
*/
Message message = Message.obtain();
message.obj = bm;
handler.sendMessage(message);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
if (bis != null) {
bis.close();
}
if (bos != null) {
bos.close();
}
if (conn != null) {
conn.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 获取图片的本地存储路径。
*
* @param imageUrl
* 图片的URL地址。
* @return 图片的本地存储路径。
*/
private String getImagePath(String imageUrl) {
int lastSlashIndex = imageUrl.lastIndexOf("/");
String imageName = imageUrl.substring(lastSlashIndex + 1);
String imageDir = Environment.getExternalStorageDirectory()
.getPath() + "/URLDemo/";
File file = new File(imageDir);
if (!file.exists()) {
file.mkdirs();
}
String imagePath = imageDir + imageName;
return imagePath;
}
最后要注意的是,在执行file.mkdirs();要增加权限,增加的如下:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>