从网络加载图片后处理图片源码

来源:互联网 发布:何多苓 知乎 编辑:程序博客网 时间:2024/05/17 22:04


import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;

public class ImageHelp {

    private  ImageView imgView;
    public  void setBitmap(ImageView view,String urlStr){
        imgView=view;
        final String urlPath=urlStr;
        new Thread(new Runnable() {
            
            @Override
            public void run() {
                String url =urlPath;  
                 Bitmap bitmap = getHttpBitmap(url);  
                 Message message=handler.obtainMessage();
                message.arg1=1;
                message.obj=bitmap;
                message.sendToTarget();
            }
        }).start();
    }
     private  Bitmap getHttpBitmap(String url){  
            URL myFileURL;  
            Bitmap bitmap=null;  
            try{  
                myFileURL = new URL(url);  
               //获得连接  
                HttpURLConnection conn=(HttpURLConnection)myFileURL.openConnection();  
                //设置超时时间为6000毫秒,conn.setConnectionTiem(0);表示没有时间限制  
                conn.setConnectTimeout(6000);  
                //连接设置获得数据流  
                conn.setDoInput(true);  
                //不使用缓存  
               conn.setUseCaches(false);  
               //这句可有可无,没有影响  
                //conn.connect();  
                //得到数据流  
                InputStream is = conn.getInputStream();  
                //解析得到图片  
                bitmap = BitmapFactory.decodeStream(is);  
               //关闭数据流  
               is.close();  
            }catch(Exception e){  
                e.printStackTrace();  
            }  
              
            return bitmap;  
              
        }
     private  Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            switch (msg.arg1) {
            case 1:
                Bitmap bitmap=(Bitmap) msg.obj;
                imgView.setImageBitmap(bitmap);  
                break;

            default:
                break;
        }
    };
};
}

0 0