码迷,mamicode.com
首页 > 其他好文 > 详细

异步获取网络图片Bitmap

时间:2015-08-20 15:20:57      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:异步   bitmap   

从网路获取图片,使用AsyncTask异步通信。

异步代码如下:

    public void addTask(String url) {
        new AsyncTask<String, Void, Bitmap>() {

            @Override
            protected Bitmap doInBackground(String... params) {
                // 后台通信
                return decodeBitmap(params[0]);
//                return byteBitmap(params[0]);
            }

            @Override
            protected void onPostExecute(Bitmap bitmap) {
                // 主线程处理view
                if (bitmap != null) {
                    mTestImage.setImageBitmap(bitmap);
                }
            }
        }.execute(url);
    }

后台处理方法

方法一:使用 BitmapdecodeStream(InputStream is) 

    private Bitmap decodeBitmap(String httpUrl) {
        URL url = null;
        Bitmap bm = null;
        try {
            url = new URL(httpUrl);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        try {
            InputStream in = url.openStream();
            bm = BitmapFactory.decodeStream(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bm;
    }

方法二:使用BitmapFactory.decodeByteArray(data,0,data.length)

    private Bitmap byteBitmap(String httpUrl) {
        Bitmap bitmap = null;
        try {
            HttpURLConnection connection = (HttpURLConnection)(new URL(httpUrl)).openConnection();
            connection.setDoInput(true);
            connection.connect();
            InputStream is = connection.getInputStream();
            try {
                byte[] data = readStream(is);
                if(data != null){
                    bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                is.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bitmap;
    }
    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();
    }







版权声明:本文为博主原创文章,未经博主允许不得转载。

异步获取网络图片Bitmap

标签:异步   bitmap   

原文地址:http://blog.csdn.net/liucaoye/article/details/47806971

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!