0816

来源:互联网 发布:nginx 静态文件服务器 编辑:程序博客网 时间:2024/06/01 21:59
package com.example.wuzijing0816;import android.app.ProgressDialog;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.os.Environment;import android.os.Handler;import android.os.Message;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.ImageView;import android.widget.Toast;import java.io.BufferedOutputStream;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;public class MainActivity extends AppCompatActivity {    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 = "http://img.juhe.cn/cookbook/s/1/45_c25e0cedd2012f45.jpg";    @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();            }        });    }    public void clearData(View view) {        File dirFile = new File(ALBUM_PATH + "/" + filePath);        if (!dirFile.exists()) {            return;        }        if (dirFile.isDirectory()) {            String[] children = dirFile.list();            for (int i = 0; i < children.length; i++) {                new File(dirFile, children[i]).delete();            }        }        dirFile.delete();        if (dirFile.delete()) {            Toast.makeText(MainActivity.this, "成功", Toast.LENGTH_SHORT).show();        }    }    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();    }    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);//        Log.e("--------------------------------------", 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();        }    };    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!", Toast.LENGTH_SHORT).show();                }                // 方法2:取得的是InputStream,直接从InputStream生成bitmap                mBitmap = BitmapFactory.decodeStream(getImageStream(filePath));                // 发送消息,通知handler在主线程中更新UI                connectHanlder.sendEmptyMessage(0);            } catch (Exception e) {                Toast.makeText(MainActivity.this, "无法连接网络", Toast.LENGTH_SHORT).show();                e.printStackTrace();            }        }    };    private Handler connectHanlder = new Handler() {        @Override        public void handleMessage(Message msg) {            // 更新UI,显示图片            if (mBitmap != null) {                mImageView.setImageBitmap(mBitmap);            }        }    };}//}