下载图片并保存到SD卡中

本文实现功能:先显示图片,然后点击下载图片按钮,执行下载功能,并保存到SD卡的指定目录。

从网络上取得的图片,生成Bitmap时有两种方法,一种是先转换为byte[],再生成bitmap,另一种是直接用InputStream生成bitmap。

activity_main.xml,只有一个按钮和一个图片

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btnSave"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="保存图片" />

    <ImageView
        android:id="@+id/imgSource"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true" />

</LinearLayout>

对应的MainActivity代码

public class MainActivity extends Activity {

	private final static String ALBUM_PATH = Environment
			.getExternalStorageDirectory() + "/download_test/";
	private ImageView mImageView;
	private Button mBtnSave;
	private ProgressDialog mSaveDialog = null;
	private Bitmap mBitmap;
	private String mFileName;
	private String mSaveMessage;
	private String filePath = "图片地址";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		mImageView = (ImageView) findViewById(R.id.imgSource);
		mBtnSave = (Button) findViewById(R.id.btnSave);

		new Thread(connectNet).start();

		// 下载图片
		mBtnSave.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				mSaveDialog = ProgressDialog.show(MainActivity.this, "保存图片",
						"图片正在保存中,请稍等...", true);
				new Thread(saveFileRunnable).start();
			}
		});
	}

	// 方法1
	public byte[] getImage(String path) throws Exception {
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(5 * 1000);
		conn.setRequestMethod("GET");
		InputStream inStream = conn.getInputStream();
		if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
			return readStream(inStream);
		}
		return null;
	}

	public static byte[] readStream(InputStream inStream) throws Exception {
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = inStream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		outStream.close();
		inStream.close();
		return outStream.toByteArray();
	}

	// 方法2
	public InputStream getImageStream(String path) throws Exception {
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(5 * 1000);
		conn.setRequestMethod("GET");
		if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
			return conn.getInputStream();
		}
		return null;
	}

	public void saveFile(Bitmap bm, String fileName) throws IOException {
		File dirFile = new File(ALBUM_PATH);
		if (!dirFile.exists()) {
			dirFile.mkdir();
		}
		File myCaptureFile = new File(ALBUM_PATH + fileName);
		BufferedOutputStream bos = new BufferedOutputStream(
				new FileOutputStream(myCaptureFile));
		bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
		bos.flush();
		bos.close();
	}

	private Runnable saveFileRunnable = new Runnable() {
		@Override
		public void run() {
			try {
				saveFile(mBitmap, mFileName);
				mSaveMessage = "图片保存成功";
			} catch (IOException e) {
				mSaveMessage = "图片保存失败";
				e.printStackTrace();
			}
			messageHandler.sendMessage(messageHandler.obtainMessage());
		}
	};

	private Handler messageHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			mSaveDialog.dismiss();
			Toast.makeText(MainActivity.this, mSaveMessage, Toast.LENGTH_SHORT)
					.show();
		}
	};

	// 连接网络 4.0中不允许在主线程中访问网络,需要在子线程中访问
	private Runnable connectNet = new Runnable() {
		@Override
		public void run() {
			try {
				mFileName = "test.jpg";

				// 以下是取得图片的两种方法
				// 方法1:取得的是byte数组, 从byte数组生成bitmap
				byte[] data = getImage(filePath);
				if (data != null) {
					mBitmap = BitmapFactory.decodeByteArray(data, 0,
							data.length);
				} else {
					Toast.makeText(MainActivity.this, "Image error!", 1).show();
				}

				// 方法2:取得的是InputStream,直接从InputStream生成bitmap
				mBitmap = BitmapFactory.decodeStream(getImageStream(filePath));

				// 发送消息,通知handler在主线程中更新UI
				connectHanlder.sendEmptyMessage(0);
			} catch (Exception e) {
				Toast.makeText(MainActivity.this, "无法连接网络", 1).show();
				e.printStackTrace();
			}
		}
	};

	private Handler connectHanlder = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// 更新UI,显示图片
			if (mBitmap != null) {
				mImageView.setImageBitmap(mBitmap);
			}
		}
	};
}

AndroidManifest.xml增加以下权限配置

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />

猜你喜欢

转载自eric-gao.iteye.com/blog/2086282
今日推荐