Android http网址链接图片的处理及显示

来源:互联网 发布:vmware player linux 编辑:程序博客网 时间:2024/05/08 03:37

1、新建一个Util类

import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.util.Log;import java.io.IOException;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.URL;public class Util {   public static String TAG="UTIL";   public static Bitmap getbitmap(String imageUri) {      Log.v(TAG, "getbitmap:" + imageUri);      // 显示网络上的图片      Bitmap bitmap = null;      try {         URL myFileUrl = new URL(imageUri);         HttpURLConnection conn = (HttpURLConnection) myFileUrl               .openConnection();         conn.setDoInput(true);         conn.connect();         InputStream is = conn.getInputStream();         bitmap = BitmapFactory.decodeStream(is);         is.close();         Log.v(TAG, "image download finished." + imageUri);      } catch (IOException e) {         e.printStackTrace();         Log.v(TAG, "getbitmap bmp fail---");         return null;      }      return bitmap;   }}
2、在要显示的类中写下面的代码:

private ImageView mUserlogo;private Bitmap mBitmap = null;/** * 获取头像 */private void getBitmap(final JSONObject response){    new Thread(){        @Override        public void run() {            try {                mBitmap = Util.getbitmap(response.getString("figureurl_qq_2"));            } catch (JSONException e) {                e.printStackTrace();            }            Message msg = new Message();            msg.obj = mBitmap;            msg.what = 1;            mHandler.sendMessage(msg);        }    }.start();}
private Handler mHandler = new Handler() {    @Override    public void handleMessage(Message msg) {        if(msg.what == 1){            Bitmap bitmap = (Bitmap)msg.obj;            mUserlogo.setImageBitmap(bitmap);        }    }};

                                             
0 0