保存下载的图片

      在前一篇博客笔记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"/>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值