android 下载保存图片
引用:http://www.linuxidc.com/Linux/2011-06/37233.htm
1.java代码,下载图片的主程序
先实现显示图片,然后点击下载图片按钮,执行下载功能。
从网络上取得的图片,生成Bitmap时有两种方法,一种是先转换为byte[],再生成bitmap;一种是直接用InputStream生成bitmap。
- publicclassAndroidTest2_3_3 extends Activity {
- privatefinalstatic String TAG = "AndroidTest2_3_3";
- privatefinalstatic String ALBUM_PATH
- = Environment.getExternalStorageDirectory() + "/download_test/";
- private ImageView imageView;
- private Button btnSave;
- private ProgressDialog myDialog = null;
- private Bitmap bitmap;
- private String fileName;
- private String message;
- @Override
- protectedvoid onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- imageView = (ImageView)findViewById(R.id.imgSource);
- btnSave = (Button)findViewById(R.id.btnSave);
- String filePath = "http://hi.csdn.net/attachment/201105/21/134671_13059532779c5u.jpg";
- fileName = "test.jpg";
- try {
- //////////////// 取得的是byte数组, 从byte数组生成bitmap
- byte[] data = getImage(filePath);
- if(data!=null){
- bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);// bitmap
- imageView.setImageBitmap(bitmap);// display image
- }else{
- Toast.makeText(AndroidTest2_3_3.this, "Image error!", 1).show();
- }
- ////////////////////////////////////////////////////////
- //******** 取得的是InputStream,直接从InputStream生成bitmap ***********/
- bitmap = BitmapFactory.decodeStream(getImageStream(filePath));
- if (bitmap != null) {
- imageView.setImageBitmap(bitmap);// display image
- }
- //********************************************************************/
- Log.d(TAG, "set image ...");
- } catch (Exception e) {
- Toast.makeText(AndroidTest2_3_3.this,"Newwork error!", 1).show();
- e.printStackTrace();
- }
- // 下载图片
- btnSave.setOnClickListener(new Button.OnClickListener(){
- publicvoid onClick(View v) {
- myDialog = ProgressDialog.show(AndroidTest2_3_3.this, "保存图片", "图片正在保存中,请稍等...", true);
- new Thread(saveFileRunnable).start();
- }
- });
- }
- /**
- * Get image from newwork
- * @param path The path of image
- * @return byte[]
- * @throws Exception
- */
- publicbyte[] 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);
- }
- returnnull;
- }
- /**
- * Get image from newwork
- * @param path The path of image
- * @return InputStream
- * @throws Exception
- */
- 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();
- }
- returnnull;
- }
- /**
- * Get data from stream
- * @param inStream
- * @return byte[]
- * @throws Exception
- */
- publicstaticbyte[] readStream(InputStream inStream) throws Exception{
- ByteArrayOutputStream outStream = new ByteArrayOutputStream();
- byte[] buffer = newbyte[1024];
- int len = 0;
- while( (len=inStream.read(buffer)) != -1){
- outStream.write(buffer, 0, len);
- }
- outStream.close();
- inStream.close();
- return outStream.toByteArray();
- }
- /**
- * 保存文件
- * @param bm
- * @param fileName
- * @throws IOException
- */
- publicvoid 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
- publicvoid run() {
- try {
- saveFile(bitmap, fileName);
- message = "图片保存成功!";
- } catch (IOException e) {
- message = "图片保存失败!";
- e.printStackTrace();
- }
- messageHandler.sendMessage(messageHandler.obtainMessage());
- }
- };
- private Handler messageHandler = new Handler() {
- @Override
- publicvoid handleMessage(Message msg) {
- myDialog.dismiss();
- Log.d(TAG, message);
- Toast.makeText(AndroidTest2_3_3.this, message, Toast.LENGTH_SHORT).show();
- }
- };
- }
2.main.xml文件,只有一个button和一个ImageView
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:Android="http://schemas.android.com/apk/res/android"
- Android:orientation="vertical"
- Android:layout_width="fill_parent"
- Android:layout_height="fill_parent"
- >
- <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>
3.在mainfest文件中增加互联网权限和写sd卡的权限
预览图: