Test

1 publicclass TestActivity extends Activity {    privatefinalstatic String TAG = "IcsTestActivity";    privatefinalstatic 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; 2 3 4    @Override    protectedvoid onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState); 5        setContentView(R.layout.main); 6 7        mImageView = (ImageView)findViewById(R.id.imgSource); 8        mBtnSave = (Button)findViewById(R.id.btnSave);        new Thread(connectNet).start();        // 下载图片 9        mBtnSave.setOnClickListener(new Button.OnClickListener(){            publicvoid onClick(View v) { 10                mSaveDialog = ProgressDialog.show(IcsTestActivity.this, "保存图片", "图片正在保存中,请稍等...", true);                new Thread(saveFileRunnable).start(); 11        } 12        }); 13    }    /** 14     * Get image from newwork 15     * @param path The path of image 16     * @return byte[] 17     * @throws Exception     */publicbyte[] getImage(String path) throws Exception{ 18        URL url = new URL(path); 19        HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 20        conn.setConnectTimeout(5 * 1000); 21        conn.setRequestMethod("GET"); 22        InputStream inStream = conn.getInputStream();        if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){            return readStream(inStream); 23        }        returnnull; 24    }    /** 25     * Get image from newwork 26     * @param path The path of image 27     * @return InputStream 28     * @throws Exception     */public InputStream getImageStream(String path) throws Exception{ 29        URL url = new URL(path); 30        HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 31        conn.setConnectTimeout(5 * 1000); 32        conn.setRequestMethod("GET");        if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){            return conn.getInputStream(); 33        }        returnnull; 34    }    /** 35     * Get data from stream 36     * @param inStream 37     * @return byte[] 38     * @throws Exception     */publicstaticbyte[] readStream(InputStream inStream) throws Exception{ 39        ByteArrayOutputStream outStream = new ByteArrayOutputStream();        byte[] buffer = newbyte[1024];        int len = 0;        while( (len=inStream.read(buffer)) != -1){ 40            outStream.write(buffer, 0, len); 41        } 42        outStream.close(); 43        inStream.close();        return outStream.toByteArray(); 44    }    /** 45     * 保存文件 46     * @param bm 47     * @param fileName 48     * @throws IOException     */publicvoid saveFile(Bitmap bm, String fileName) throws IOException { 49        File dirFile = new File(ALBUM_PATH);        if(!dirFile.exists()){ 50            dirFile.mkdir(); 51        } 52        File myCaptureFile = new File(ALBUM_PATH + fileName); 53        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile)); 54        bm.compress(Bitmap.CompressFormat.JPEG, 80, bos); 55        bos.flush(); 56        bos.close(); 57    }    private Runnable saveFileRunnable = new Runnable(){ 58        @Override        publicvoid run() {            try { 59                saveFile(mBitmap, mFileName); 60                mSaveMessage = "图片保存成功!"; 61            } catch (IOException e) { 62                mSaveMessage = "图片保存失败!"; 63                e.printStackTrace(); 64            } 65            messageHandler.sendMessage(messageHandler.obtainMessage()); 66        } 67 68    };    private Handler messageHandler = new Handler() { 69        @Override        publicvoid handleMessage(Message msg) { 70            mSaveDialog.dismiss(); 71            Log.d(TAG, mSaveMessage); 72            Toast.makeText(IcsTestActivity.this, mSaveMessage, Toast.LENGTH_SHORT).show(); 73        } 74    };    /* 75     * 连接网络 76     * 由于在4.0中不允许在主线程中访问网络,所以需要在子线程中访问     */private Runnable connectNet = new Runnable(){ 77        @Override        publicvoid run() {            try { 78                String filePath = "http://img.my.csdn.net/uploads/201211/21/1353511891_4579.jpg"; 79                mFileName = "test.jpg";                //以下是取得图片的两种方法//////////////// 方法1:取得的是byte数组, 从byte数组生成bitmapbyte[] data = getImage(filePath);                if(data!=null){ 80                    mBitmap = BitmapFactory.decodeByteArray(data, 0, data.length);// bitmap 81                }else{ 82                    Toast.makeText(IcsTestActivity.this, "Image error!", 1).show(); 83                }                //////////////////////////////////////////////////////////******** 方法2:取得的是InputStream,直接从InputStream生成bitmap ***********/ 84                mBitmap = BitmapFactory.decodeStream(getImageStream(filePath));                //********************************************************************/                // 发送消息,通知handler在主线程中更新UI 85                connectHanlder.sendEmptyMessage(0); 86                Log.d(TAG, "set image ..."); 87            } catch (Exception e) { 88                Toast.makeText(IcsTestActivity.this,"无法链接网络!", 1).show(); 89                e.printStackTrace(); 90            } 91 92        } 93 94    };    private Handler connectHanlder = new Handler() { 95        @Override        publicvoid handleMessage(Message msg) { 96            Log.d(TAG, "display image");            // 更新UI,显示图片if (mBitmap != null) { 97                mImageView.setImageBitmap(mBitmap);// display image            } 98        } 99    }; 100 101} 102 103<?xml version="1.0" encoding="utf-8"?> 104<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 105    android:orientation="vertical" 106    android:layout_width="fill_parent" 107    android:layout_height="fill_parent"> 108<Button        android:id="@+id/btnSave" 109          android:layout_width="wrap_content"  110        android:layout_height="wrap_content" 111        android:text="保存图片"/> 112<ImageView        android:id="@+id/imgSource" 113          android:layout_width="wrap_content"  114        android:layout_height="wrap_content"  115        android:adjustViewBounds="true"/></LinearLayout>
点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )