Android读取网络图片

/**
	 * 读取网络图片
	 * 
	 * @author ysh
	 * 
	 */
	public static Bitmap getBitmap(String url) {
		Bitmap bt = null;
		if (url != null && !url.equals("")) {
			InputStream is = null;
			try {
				URL url1 = new URL(url);
				HttpURLConnection conn = (HttpURLConnection) url1
						.openConnection();

				conn.setDoInput(true);
				conn.connect();
				is = conn.getInputStream();
				bt = BitmapFactory.decodeStream(is);
				is.close();
				conn.disconnect();

			} catch (MalformedURLException e) {
				e.printStackTrace();
				return bt;
			} catch (IOException e) {
				e.printStackTrace();
				return bt;
			}

		}

		return bt;

	}

private Bitmap mBitmap;


try {
	json = HttpDownload.getJSONData(url);
	JSONObject root;
	try {
		root = new JSONObject(json.toString());
		String items = root.getString("ImageUrl");// 获取服务端json中数据
		Integer count = Integer.parseInt(root.getString("Count"));
		if (count == 0) {
			mBitmap = BitmapFactory.decodeFile(filePath_old);
		} else {
			Log.i("======= :", "" + items);
			String img_url = items;
			String fileName = img_url.substring(
					img_url.lastIndexOf('/') + 1, img_url.length());// 提取下载图片的文件名
			mBitmap = Commons.getBitmap(img_url);
			DeleteFile(filePath_old);
			saveFile(mBitmap, fileName);
		}
	} catch (JSONException e) {
		e.printStackTrace();
	}
} catch (ClientProtocolException e) {
	e.printStackTrace();
} catch (IOException e) {
	e.printStackTrace();
}

Drawable draw = new BitmapDrawable(mBitmap);
imgView.setBackgroundDrawable(draw);

猜你喜欢

转载自yebingzi.iteye.com/blog/1661510