保存下载的图片

来源:互联网 发布:诗歌鉴赏答题技巧软件 编辑:程序博客网 时间:2024/05/14 23:30
      在前一篇博客笔记HttpURLConnection下载网络图片中学习了下载并显示网络上的一张图片,在此基础上怎么保存该网络图片,关键代码如下:
private void downloadPicture(){String urlStr = "http://img.my.csdn.net/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 blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.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"/>
0 0